george
george

Reputation: 13

How do i check if input is an int in C++?

If the input is an integer, I want to set it equal to an integer variable.

If the input is a string, I will want to set it to a string variable, and later check if the string is "quit".

I don't know how to check it. I've looked for a built in function and found nothing.

while (true) {

    int numberEntered;
    string stringEntered; 

    cout << "enter a number to see if it is greater than 5: \n or enter \'quit\' to exit the program";

    //I don't know what to do below here
    cin >> ;

    if (stringEntered == "quit") {
        break;
    }

    if (numberEntered > 5) {
        cout << "that number is greater than 5" << endl;
    }
    else {
        cout << "not greater than 5" << endl;
    }
}

Upvotes: 0

Views: 149

Answers (2)

M.M
M.M

Reputation: 141554

David S.'s answer is good. If you want to tidily handle garbage being entered after the line, here is another option (this is more complicated for your situation, but if you later want to expand your program to handle a lot of different input, then this way may come out to be simpler).

while( true )
{
    string stringEntered;
    cout << "enter a number to see if it is greater than 5: \n or enter \'quit\' to exit the program: " << flush;

// read the whole line, this ensures no garbage remains in the input stream
    getline(cin, stringEntered);

    if ( stringEntered == "quit" )
        break;

// this checks that a number was entered and nothing else
    istringstream iss(stringEntered);
    int numberEntered;
    char ch;
    if ( !(iss >> numberEntered) || (iss >> ch) )
    {
        cout << "please try again. ";
        continue;
    }

// process the number
    cout << "that number is " << (numberEntered > 5 ? "" : "not ")
            << "greater than 5." << endl;
}

You may need #include <sstream>.

Upvotes: 0

David S.
David S.

Reputation: 538

cin >> numberEntered;
if (!cin.fail())
{
   ...

It may be more idiomatic to use:

if (cin >> numberEntered)

Upvotes: 2

Related Questions