Hi,
I've just started learning c++ and I've been playing with cin/cout to get me started.
I wanted to write some code that asks the user to enter an integer - if they fail to do this then they are prompted again to enter an integer. So I wrote the following:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
int value;
do {
// called at start of loop iteration
cin.clear();
cout << "Please enter an integer value: " << endl;
cin >> value;
} while ( cin.fail() );
cout << "Number entered was: " << value << endl;
|
When I run this and enter an integer then the program terminates as expected.
If I enter a character instead then the loop runs forever without allowing me to make another entry.
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
Please enter an integer value:
etc...
|
I could understand this if the cin.clear() was not used as the previous input would still exist in the buffer, but my understand was that cin.clear() would flush the input buffer thus allowing me to make another entry.
What I find more confusing is that if (as a test) I execute cin.clear() at the end of the loop iteration then it appears to clear the buffer as expected, (although this no longer delivers the desired functionality):
1 2 3 4 5 6 7 8 9
|
do {
cout << "Please enter an integer value: " << endl;
cin >> value;
// called at end of loop iteration
cin.clear();
} while ( cin.fail() );
|
Using the above code the loop is terminated no matter what is entered.
Does the context of cin change once a new loop iteration has been entered?
What is the difference between executing cin.clear() at the end of the current iteration or at the beginning of the next iteration?
Please help!
Thanks,
Vince.