In the first example, he uses
cin.getline(c, 1000);
, and in the second
cin >> choice;
.
However, the problem is that you are trying to use
formatted input when the user is using
line input.
That is,
the user expects that he must press Enter after every input. This is a line-based input method.
Your program should also get input in this way, and
then parse the string using formatted input methods.
1 2 3 4 5 6 7 8 9
|
int x;
string users_input; // could be anything!
do
{
cout << "Please enter an integer> " << flush;
getline( cin, users_input );
}
while (!(istringstream( users_input ) >> x));
cout << "Good job! You entered the integer '" << x << "'.\n";
|
You'll notice that this example accepts nothing less than an integer.
(It may accept
more. For example, "42 is a valid answer" works, accepting the value '42' and ignoring everything else. See
http://www.cplusplus.com/forum/beginner/13044/page1.html#msg62827 for more. And here's a related post:
http://www.cplusplus.com/forum/beginner/13562/ .)
The problem with the infinite looping is a direct consequence of failing to observe the above rubric. Given something like:
1 2 3 4 5 6 7 8
|
// B A D C O D E !
int num;
do
{
cout << "Enter any number except '12'> " << flush;
cin >> num;
}
while (num != 12);
|
This code fails catestrophically if the user enters anything other than a valid number.
Why? Because once an invalid input is encountered, the input stream (in this case,
cin) is signaled to a
fail state -- meaning that it will not receive any more input, and you will loop forever. Unless, by some miracle, the
num variable happened to have the random value '12' before your user entered bad input.
You must always check against bad input.
And you must always accept input according to the user's expectations.
Hope this helps.
[edit] Aw man! Too slow...