1 #include <iostream>
2 #include <fstream>
3
4 using namespace std;
5
6 void check_cin (istream &is)
7 {
8 if(is.bad())//系统级的错误才会bad
9 {
10 cout<<"cin bad()"<<endl;
11 }else{
12 cout<<"cin not bad()"<<endl;
13 }
14
15 if(is.fail())//
16 {
17 cout<<"cin fail()"<<endl;
18 }else{
19 cout<<"cin not fail()"<<endl;
20 }
21
22 if(is.eof())//输入结束的时候是eof
23 {
24 cout<<"cin eof()"<<endl;
25 }else{
26 cout<<"cin not eof()"<<endl;
27 }
28
29
30 if(is.good())//
31 {
32 cout<<"cin good()"<<endl;
33 }else{
34 cout<<"cin not good()"<<endl;
35 }
36
37 }
38
39 int main()
40 {
41 cout<<"检查cin的状态,一下四个状态"<<endl;
42 // cin.setstate(istream::badbit); //强制将流的状态设置为bad
43 // cin.setstate(istream::failbit);
44 // cin.setstate(istream::badbit | istream::failbit);
45 // cin.clear(istream::badbit)//可以清除某一个状态
46
47
48 // istream::iostate old_state=cin.rdstate();//将流的状态保存下来
49 // .........
50 // cin.clear(old_state)//用完以后然后还原成原来保存下来的状态
51
52
53
54 check_cin(cin);
55 cout<<"请输入一个数"<<endl;
56 int n;
57 cin>>n;
58 cout<<"再次检查状态"<<endl;
59 check_cin(cin);
60
61 cout<<"============================="<<endl;
62 int i=0,val;
63 // while(cin>>val)
64 // {
65 // i+=val;
66 // cout<<"sum is"<<i<<endl;
67 // }
68
69 while(cin>>val,!cin.eof())
70 {
71 if(cin.bad())
72 {
73 throw runtime_error("IO CORRUPED");
74 }
75 if(cin.fail())
76 {
77 cout<<"输入的数据是错的"<<endl;
78 cin.clear(); //清空恢复成正常的流
79 cin.ignore(200,'\n'); //对不对的数据进行清除要么是200个要么是换行
80 continue; //继续循环
81 }
82 i+=val;
83 cout<<"sum is"<<i<<endl;
84 }
85
86 return 0;
87 //预处理进行调试
88 #ifdef NDEBUG
89 cout<<""<<endl;
90 #endif // NDEBUG
91 }
来源:https://www.cnblogs.com/yh2924/p/12596437.html