Thread: "is Integer" function

  1. #1
    Registered User
    Join Date
    Mar 2006

    "is Integer" function

    Hey everyone

    I'm writing this program for school, and i have a question:
    How do i make sure that a value that the user entered is an integer and not a char or something else?
    Is there a function that verifies this? something like:

    if ( !isInteger(value) )
    Or something like that?



  2. #2
    Registered User
    Join Date
    Jan 2005
    If you are inputting through cin, then you can do this as you read in the input. You can add more and more checks to it to be more and more strict, but the basic premise is:
    int value = 0;
    while (!(cin >> value))
        cin.ignore(1000, '\n');
        cout << "Invalid input, try again: ";
    That works because cin >> evaluates to false if the read failed (like if you are expecting an int and the user types a char). It then enters the while loop where the cin stream is cleared of the error and the bad input is ignored.

    You could also make an isInteger method that takes a string and does the same thing with a stringstream, but that probably is overkill for a school assignment.

  3. #3
    Registered User
    Join Date
    Apr 2003
    Is there a function that verifies this?
    There are no functions in C++: it's a do-it-yourself language. Try Java.

  4. #4
    Join Date
    Jan 2006
    That's what makes C++ so popular

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  3. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 06:54 PM
  4. Change this program so it uses function??
    By stormfront in forum C Programming
    Replies: 8
    Last Post: 11-01-2005, 08:55 AM
  5. const at the end of a sub routine?
    By Kleid-0 in forum C++ Programming
    Replies: 14
    Last Post: 10-23-2005, 06:44 PM