Thread: Check if 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,897
    >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-05-2010, 11:42 PM
  2. Check for integer in kernel module
    By NuNn in forum C Programming
    Replies: 1
    Last Post: 04-13-2009, 11:27 AM
  3. Check if a string is a positive integer, please help.
    By Phantom2303 in forum C Programming
    Replies: 1
    Last Post: 03-16-2009, 09:55 PM
  4. MFC check box question
    By MyglyMP2 in forum Windows Programming
    Replies: 2
    Last Post: 03-09-2009, 05: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