#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()
,程序将进入无限循环
最佳答案
cin.ignore();
cin.clear();
/* Input the number from the user*/
cout << "Enter number\n";
cin >> a;
至
/* Input the number from the user*/
cout << "Enter number\n";
cin.clear();
cin.ignore();
cin >> a;
关于c++ - 需要额外的换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16208992/