ca77a_c++__一个打开并检查文件输入的程序_流对象_操作文件

/*ca77a_c++__一个打开并检查文件输入的程序

习题:8.13 8.14
*/

 1 /*ca77a_c++__一个打开并检查文件输入的程序
 2 
 3 习题:8.13  8.14
 4 */
 5 
 6 #include <iostream>
 7 #include <fstream>
 8 #include <string>
 9 #include "get.h"
10 
11 using namespace std;
12 
13 ifstream& open_file(ifstream &in, const string &file)
14 {
15     in.close();
16     in.clear();//恢复流的状态
17     in.open(file.c_str());
18     return in;
19 
20 }
21 
22 int main()
23 {
24     string fileName, s;
25     cout << "Enter filename:" << endl;
26     cin >> fileName;
27     ifstream inFile; //创建流对象inFile
28     //调用函数打开
29     if (!open_file(inFile, fileName))
30     {
31         cerr << "error: can not open file: " <<fileName<< endl;
32         return -1;
33     }
34     get(inFile);
35     inFile.close();
36     return 0;
37 }

get.cpp

 1 #include "get.h"
 2 
 3 std::istream& get(std::istream &in)//8.3
 4 {
 5     int ival;
 6     while (in >> ival, !in.eof())//让in.eof()决定是否结束,ctrl+z结束输入
 7     {
 8         if (in.bad())//巨大错误
 9             throw std::runtime_error("IO stream error");
10         if (in.fail())//判断输入类型是否相同,val是int,如果文件里面是字符,就出错。
11         {
12             std::cerr << "bad data,try again." << std::endl; //std名称空间
13             in.clear();//恢复流到正常状态
14             in.ignore(200,'\n');//
15             continue;
16         }
17         std::cout << "输入的数据: " << ival << std::endl;
18     }
19     in.clear();//恢复流到正常状态
20 }

get.h

 1 //#pragma once
 2 #ifndef _GET_H
 3 #define _GET_H
 4 
 5 //头文件不要用using namesapce std;
 6 #include <iostream>
 7 std::istream& get(std::istream &in);
 8 
 9 
10 #endif

 

原文链接: https://www.cnblogs.com/txwtech/p/12296882.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    ca77a_c++__一个打开并检查文件输入的程序_流对象_操作文件

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/328576

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月1日 下午4:45
下一篇 2023年3月1日 下午4:46

相关推荐