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

来源:互联网 发布:一件代发软件 编辑:程序博客网 时间:2024/06/04 20:00
//当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 dataint 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;}

0 0