View Full Version : [C++] Avoiding Characters Stored in an Integer

November 15th, 2008, 10:47 PM
First off, I did Google this with no good results...

I have a console program and it takes integers as options. However, when I put in a letter as an answer the program messes up. How do I prevent character(s) from being stored in an integer?

int option;
cin >> option;

November 15th, 2008, 11:14 PM
cin will not store characters in an integer.

If you query for an integer using cin, and the user enters one or more characters (followed by 'enter'), then cin will fail. You can verify this by calling cin.fail().

To clear cin's error state, you need to call cin.clear(), followed by a call to cin.ignore() remove unwanted characters from the data stream.

For example:

int value = 0;

while (true)
std::cout << "Enter a number: ";
std::cin >> value;

if (std::cin.fail())
std::cin.ignore(1024, '\n'); // ignore at most 1024 characters until '\n' found
break; // all good; we got a value

November 16th, 2008, 04:36 AM
Nevermind... I should test more before posting code.