"is Integer" function

This is a discussion on "is Integer" function within the C++ Programming forums, part of the General Programming Boards category; Hey everyone I'm writing this program for school, and i have a question: How do i make sure that a ...

  1. #1
    Registered User
    Join Date
    Mar 2006
    Posts
    2

    "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:

    Code:
    if ( !isInteger(value) )
    {
    ...
    ...
    ...
    }
    Or something like that?

    Thanks.

    Diego.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    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:
    Code:
    int value = 0;
    while (!(cin >> value))
    {
        cin.clear();
        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
    Posts
    2,662
    Is there a function that verifies this?
    There are no functions in C++: it's a do-it-yourself language. Try Java.

  4. #4
    User
    Join Date
    Jan 2006
    Location
    Canada
    Posts
    498
    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, 04:06 PM
  2. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 02:01 AM
  3. In over my head
    By Shelnutt2 in forum C Programming
    Replies: 1
    Last Post: 07-08-2008, 07: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, 07:44 PM

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