First, give the code. The original intention of this code is to input a from the keyboard, and then judge whether a is successfully read, if not, print the information, and let the user input again, until the user enters a legal input and stops.
c++ code
#include <iostream>
using namespace std;
int main() {
int a=0;
while (1) {
if (!(cin >> a))
{
cout << "I'm in the loop!\n";
}
else
break;
}
cout << a << endl;
return 0;
}
However, when the above code runs, if you enter a character instead of a number on the keyboard, it will enter an endless loop instead of receiving the user's keyboard input again after printing the information.
The explanation for this phenomenon is that illegal input causes the input stream to have a status error flag, and the input illegal characters remain in the input stream. When judging !(cin>>a)
, you will first see the input stream error mark, directly judge the condition to be established, then output that piece of information, and then enter the loop. Therefore, two things need to be done.
- Clear the error mark of the input stream
These two steps are indispensable for removing illegal characters from the input stream . So the code can be changed to this.
#include <iostream>
using namespace std;
int main() {
int a=0;
while (1) {
if (!(cin >> a))
{
cout << "I'm in the loop!\n";
cin.clear(); // 清除输入流错误标记
cin.ignore(1024,'\n');// 取走刚才输入流中的字符
// cin.ignore()默认取走一个字符
}
else
break;
}
cout << a << endl;
return 0;
}
c code
#include <cstdio>
int main() {
int a = 0;
while (1) {
if (!scanf("%d",&a))
{
printf("I'm in the loop!\n");
}
else
break;
}
printf("%d\n",a);
return 0;
}
The above code is equivalent to the C++ code, the
solution:
#include <cstdio>
int main() {
int a = 0;
while (1) {
if (!scanf("%d",&a))
{
printf("I'm in the loop!\n");
rewind(stdin);
}
else
break;
}
printf("%d\n",a);
return 0;
}