0

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; } } 
2
  • What do you want to happen if the person types "52hello" or "5 quit" or "quite a long sentence" ? Commented May 7, 2014 at 2:09
  • @Matt McNabb I was going to dela with that later. I want a message to appear that says 'try again'. Commented May 7, 2014 at 2:11

2 Answers 2

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

It may be more idiomatic to use:

if (cin >> numberEntered) 
Sign up to request clarification or add additional context in comments.

1 Comment

Expanding on this; if it turns out that cin >> numberEntered failed, then you can go cin.clear(); cin >> stringEntered; to get the next word, or cin.clear(); getline(cin, stringEntered) to get the remainder of the line.
0

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>.

3 Comments

superb. thanks. the comments help me understand. is flush important? the program works fine without it.
It depends on your compiler whether or not it works without flush
@MattMcNabb: No, it doesn't. It depends on whether you untied std::cin and std::cout. At startup, they are tied and then flushing is automatic.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.