C/c++ input stream refresh to solve the infinite loop problem caused by illegal input

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.
Insert picture description here
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.

  1. Clear the error mark of the input stream

  2. 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;
}

Insert picture description here

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;
	
}

Guess you like

Origin blog.csdn.net/Fei20140908/article/details/104880757