//当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输入错误时导致failbit为1时的缓冲区分析。
最新推荐文章于 2022-08-04 18:22:37 发布