#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();'灑一點慷慨。 – 2013-04-25 07:48:05