文件流习题8.3 8.4

将输入内容放入流中,并返回。

 

1 #ifndef _GET_H
2 #define _GET_H
3 
4 #include <iostream>
5 
6 std::istream& get(std::istream& in);
7 
8 
9 #endif
 1 #include "get.h"
 2 
 3 std::istream& get(std::istream& in)
 4 {
 5 
 6     int ival;
 7 
 8     while(in >> ival, !in.eof())
 9     {
10     
11         if(in.bad())
12             throw std::runtime_error("IO stream corrupted");
13         if(in.fail())
14         {
15             std::cerr << "bad data. try again!" << std::endl;
16             in.clear();
17             in.ignore(200, '\n');
18             continue;
19         }
20     std::cout << "输入的数据:" << ival << std::endl;
21 
22     }
23     in.clear();
24     return in;
25 }
 1 #include "get.h"
 2 #include <iostream>
 3 
 4 using namespace std;
 5 
 6 int main()
 7 
 8 {
 9     cout << "测试所写的函数" << endl;
10 
11     double dval;
12 
13     get(cin);
14 
15     cout << "继续使用cin,输入一个double:" << endl;
16     cin >> dval;
17     cout << "你输入的是:" << dval << endl;
18 
19     return 0;
20 }

 

posted @ 2012-12-23 16:31  uniquews  阅读(147)  评论(0编辑  收藏  举报