It's the standard input problem.
Although it is convenient to be able to write this (particularly, it is convenient to be able to
chain reads, especially from a file:
inputFile >> var1 >> var2 >> var3;
, it isn't
useful without a lot of modification.
The problem is that if the stream (std::cin) does not contain input that is integral (ie, "Hello"
is not integral, nor is "z4"), the input operation fails, x is left undefined, and the stream is
left unchanged. Which means if you attempt to read an integer a second time, the exact
same thing will happen. And again. And again. Etc.
You have to check the stream for an error after attempting to read an integer, and upon
error you have to flush the errant characters. Most people will flush until a newline,
since the user is required to press ENTER anyway.
1 2 3 4 5 6 7 8 9
|
int x;
while( 1 ) {
std::cout << "Please enter an integer: " << std::flush;
std::cin >> x;
if( !std::cin ) {
std::cout << "Invalid input entered." << std::endl;
std::cin.ignore( std::numeric_limits<streamsize>::max(), '\n' );
} else break;
}
|