Check if an Integer

This is a discussion on Check if an Integer within the C++ Programming forums, part of the General Programming Boards category; In main() say you have something like this: Code: int main(){ int a; cout << "enter an integer: " ; ...

  1. #1
    Registered User
    Join Date
    Sep 2006
    Posts
    10

    Check if an Integer

    In main()
    say you have something like this:

    Code:
     
    
    int main(){
    
    int a;
    
    cout << "enter an integer: " ;
    cin >> a;
    
    CheckIfInt(a);
    
    return 0;
    
    }
    
    void CheckIfInt(int b)
    {
    
    /// ?????
    
    }
    How would you go about checking if what the user entered is an integer? If the user not entered an integer, then repromt the user. how would one do this? I've tried coverting to ASCII, but that doesn't seem to help.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >How would you go about checking if what the user entered is an integer?
    a has integer type, so if the request for input fails then the user didn't enter an integer:
    Code:
    for ( ; ; ) {
      cout<<"Enter an integer: ";
    
      // Success
      if ( cin>> a )
        break;
      else {
        cout<<"Not an integer\n";
    
        // Clear the error state
        cin.clear();
    
        // Remove the bad characters
        cin.ignore(magic_number, '\n');
      }
    }
    My best code is written with the delete key.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. BN_CLICKED, change button style
    By bennyandthejets in forum Windows Programming
    Replies: 13
    Last Post: 07-06-2010, 12:42 AM
  2. Check for integer in kernel module
    By NuNn in forum C Programming
    Replies: 1
    Last Post: 04-13-2009, 12:27 PM
  3. Check if a string is a positive integer, please help.
    By Phantom2303 in forum C Programming
    Replies: 1
    Last Post: 03-16-2009, 10:55 PM
  4. MFC check box question
    By MyglyMP2 in forum Windows Programming
    Replies: 2
    Last Post: 03-09-2009, 06:47 PM
  5. Operator Overloading (Bug, or error in code?)
    By QuietWhistler in forum C++ Programming
    Replies: 2
    Last Post: 01-25-2006, 08:38 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21