#include <iostream>
using namespace std;
int main()
{
int a;
do
{
/* First reset the flag and then clean the buffer*/
cin.ignore();
cin.clear();
/* Input the number from the user*/
cout << "Enter number\n";
cin >> a;
/*Diplay appropiate error if the input was wrong*/
if(cin.fail())
{
cout << "invalid input \n";
}
/*Display the number if the input was valid*/
else
{
cout << "number entered is : " << a << endl;
}
}
while(cin.fail()); //repeat until the input is correct
return 0;
}
每次我执行这个程序时,我都必须先输入一个新行,然后再cout<<"Enter number\n";
执行。
其背后的原因是什么以及可能的解决方案是什么。
注意:没有cin.ignore()
程序进入无限循环