In the following loop, if we type characters as the cin
input instead of numbers which are expected, then it goes into infinite loop. Could anyone please explai
Attention
Please pay attention to the following solution. It is not complete yet to clear the error in your case. You will still get an infinite loop!
if (cin.fail())
{
cout << "Please enter an integer";
cin.clear();
}
Complete Solution
The reason is you need clear the failed state of stream, as well as discard unprocessed characters. Otherwise, the bad character is still there and you still get infinite loops. You can simply can std::cin.ignore() to achieve this. For example,
if (cin.fail())
{
cout << "Please enter an integer";
// clear error state
cin.clear();
// discard 'bad' character(s)
cin.ignore(std::numeric_limits::max(), '\n');
}
Another Solution
You can also use getline
and stringstream
to achieve. Here is a brief example.
string input;
while (1)
{
getline(cin, input);
stringstream(input) >> x;
cout << x << endl;
}