流条件状态练习

 1 #include <iostream>
 2 using namespace std;
 3 
 4 int main()
 5 {
 6     int ival;
 7     while(cin >> ival, !cin.eof())
 8     {
 9         if(cin.bad())
10             throw runtime_error("IO stream corrupted");
11         if(cin.fail())
12         {
13             cerr << "bad data, try again";
14             cin.clear(istream::failbit);
15             cin.setstate(istream::eofbit);//设置结束位结束while死循环
16             continue;
17         }
18         cout << ival << endl;
19     }
20     return 0;
21 }
 1 #include <iostream>
 2 
 3 using namespace std;
 4 
 5 istream & fun(istream &in)
 6 {
 7     int ival;
 8     while(in >> ival, !in.eof())
 9     {
10         if(in.bad())// input stream is corrupted; bail out, 流是否已被破坏
11         {
12             throw runtime_error("ERROE:IO stream corrupted");
13         }
14         if(in.fail())// bad input
15         {
16             cerr << "bad date, try again:";
17             in.clear();
18             in.setstate(istream::eofbit);// 结束死循环,如果去掉该句,当输入字符时候就会出现死循环
19             continue;
20         }
21         cout << ival << endl;
22     }
23     in.clear();// 将in中的所有状态值都设为有效状态
24     return in;
25 }
26 
27 int main()
28 {
29     cout << " Input some words ( ctrl + z to end ):
"; 
30     fun(cin);
31     return 0;
32 }
原文地址:https://www.cnblogs.com/dongsheng/p/3311616.html