热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

c++入门之文件读取

再次强调这个观念:写文件,读文件和读,写控制台本质上没有区别,意识到这一点是十分重要的。下面给出读文件的代码:1#inclu

再次强调这个观念:写文件,读文件和读,写控制台本质上没有区别,意识到这一点是十分重要的。下面给出读文件的代码:

1 #include "iostream"
2 # include "fstream"
3 # include "cstdlib"
4 const int SIZE{ 60 };
5 int main()
6 {
7 using namespace std;
8 char filename[SIZE];
9 ifstream Infile;//定义一个输入流对象,等效于cin
10 cout <<"Enter name of data file:";
11 cin.getline(filename, SIZE);//从输入流中截取最大SIZE个字符的字符串作为文件名,遇到换行符\n也会终止
12 Infile.open(filename);//打开文件
13 if (!Infile.is_open())//文件打开成功返回1
14 {
15 cout <<"could not fine the file:" < endl;
16 exit(EXIT_FAILURE);//打开失败退出系统
17 }
18
19 double value;
20 double sum{ 0.0 };
21 int count{ 0 };
22
23 Infile >> value;//注意Infile 相当于cin
24 while (Infile.good())
25 {
26 &#43;&#43;count;
27 sum &#43;&#61; value;
28 Infile >> value;
29 }
30 if (Infile.eof())//eof判断是否读到文件末尾,读到末尾返回值为1.
31 cout <<"End of file readed.\n";
32 else if (Infile.fail())
33 cout <<"missing match" << endl;
34 else
35 cout <<"input for unknowm" << endl;
36 if (count &#61;&#61; 0)
37 cout <<"No data" << endl;
38 else
39 {
40 cout <<"sum is:" < endl;
41 cout <<"average is:" < endl;
42 }
43 Infile.close();
44 system("pause");
45 return 0;
46 }

注意点&#xff1a;

对于读文件中出现的.getline&#xff08;&#xff09;方法&#xff0c;和.oef&#xff08;&#xff09;方法&#xff0c;暂时不再赘述

需要强调的是,理解23_29行的代码,尤其是23行的代码。理解:Infile >> value;首先应该认识到:Infile关联了一个文件&#xff0c;其实我们应该认识到:文件流和控制台输入流并没有一个本质的区别.因此,当我们看到Infile的时候&#xff0c;我们可以完全认为这是个cin>>value,而我们是知道cin>>value表达的是从控制条输入流中取一个类型的数据赋值给value。因此&#xff0c;这样一来&#xff0c;我们就可以完全理解Infile>>value表达的含义,从文件流中获取一个value对应类型的数据送给value。

转:https://www.cnblogs.com/shaonianpi/p/9783863.html



推荐阅读
author-avatar
曾军78930
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有