int i;
while (1)
{
cout << "input a number: ";
cin >> i;
if(cin && i >= 0 && i <= 100)
break;
else
{
cin.clear();
cout << "error" << endl;
}
}
上面这段代码中, 在要求输入i的地方, 如果输入了非数字, 就会造成死循环. 具体原因在于非数字字符仍然保留在缓冲区中, 所以当下一次cin读取的时候, 就直接从缓冲区中读取, 这样一直循环, 每次都是读取的非数字字符, 造成了死循环. 修改else里面的语句为:
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '/n');
cout << "error" << endl;
}
ignore()的作用主要是从缓冲区中取字符并丢弃, 就起到了刷新缓冲区的作用.
/* C++ 版本 */
#include <iostream>
#include <limits> // 为了使用numeric_limits
using std::cout;
using std::endl;
using std::cin;
using std::numeric_limits;
using std::streamsize;
int main()
{
int value;
for ( ; ; )
{
cout << "Enter an integer: ";
cin >> value;
if ( cin.eof() || cin.bad() )
{ // 如果用户输入文件结束标志(或文件已被读完),
// 或者发生读写错误,则退出循环
// do something
break;
}
// 读到非法字符后,输入流将处于出错状态,
// 为了继续获取输入,首先要调用 clear 函数
// 来清除输入流的错误标记,然后才能调用
// ignore 函数来清除输入流中的数据。
cin.clear();
// numeric_limits<streamsize>::max() 返回输入缓冲的大小。
// ignore 函数在此将把输入流中的数据清空。
// 这两个函数的具体用法请读者自行查询。
cin.ignore( numeric_limits<streamsize>::max(), '/n' );
cout << value << '/n';
}
return 0;
}