您的位置:首页 > 大数据 > 人工智能

cin输入错误时导致failbit为1时的缓冲区分析。

2016-01-06 10:04 716 查看
//当cin尝试将输入的字符读为int型数据失败后,会产生一个错误状态

//会把cin的failbit设定为1,所以会出现cin错误。所以must i?

//依然会留在缓冲区中(由此我们可以做一个假定当输入触发cin中的failbit

//为1时,数据仍然留在缓冲区中并没有被丢弃)

//要使程序能够继续正常工作需要用clear清除failbit状态

#include <iostream>
using namespace std;
const int Max = 5;
int main()
{

//using namespace std;
//get data
int golf[Max];
cout<< "Please enter your golf scores.\n";
cout << "you must enter " << Max << " round.\n";
int i;
for (i = 0; i < Max; i++)
{
cout << "round # " << i + 1 << ": ";
while (!(cin>> golf[i]))
{
cin.clear();
char ch;
while ((ch=cin.get()) != '\n')
{
cout << ch << "Look!\n";
continue;
}
cout << "Please enter a number: ";
}
}

double total = 0.0;
for (i = 0; i < Max; i++)
total += golf[i];

cout << total / Max << " = average score " << Max << " rounds\n";

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cin