c++入门之文件读取

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

 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:" << filename << 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         ++count;
27         sum += 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 == 0)
37         cout << "No data" << endl;
38     else
39     {
40         cout << "sum is:" << sum << endl;
41         cout << "average is:" << sum / count << endl;
42     }
43     Infile.close();
44         system("pause");
45         return 0;
46 }

注意点:

对于读文件中出现的.getline()方法,和.oef()方法,暂时不再赘述

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

猜你喜欢

转载自www.cnblogs.com/shaonianpi/p/9783863.html