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
欢迎讨论,相互学习。
cdtxw@foxmail.com
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)