C++文本数据读取

来源:互联网 发布:net.sf.json官方下载 编辑:程序博客网 时间:2024/05/17 22:32

读取文本数据的时候,其相应的流程与写入颇为相似,但也有一些区别,毕竟是两个不同的功能。

1.添加必须的头文件:#include <fstream> 、#include <cstdlib>。

2.定义相应的数组,用于存储文件的名称。

3.定义相应的变量,用于存储文件写入的数据。

4.创建一个ifstream对象。

5.将ifstream与文本文件进行关联。

6.测试文件打开是否正常。

7.使用ifstream对象和<<运算符进行数据写入。

8.使用完ifstream对象后关闭。

以一个遍历文本所有数据,并计算所占字符的程序作为实例:

#include <iostream>#include <fstream>// file I/O support#include <cstdlib>// support for exitconst int SIZE = 60;int main(){using namespace std;char filename[SIZE];char ch;ifstream inFile;// object for handing file inputcout << "Enter name of data file: ";cin.getline(filename,SIZE);inFile.open(filename);// associate inFile with a fileif(!inFile.is_open())// failed to open file{cout << "Could not open the file " << filename << endl;cout << "program terminating.\n";exit(EXIT_FAILURE);}int sum = 0;// number of items readinFile >> ch;while(inFile.good())// while input good not at EOF{sum++;inFile >> ch;}cout << sum << " characters in " << filename << endl;inFile.close();// done with the filereturn 0;}

在测试文件是否正常打开时,若是打开失败的话,就要终止程序的运行,这里用到了#include <cstdlib>头文件,程序中所对应的语句exit(EXIT_FAILURE);有了它,妈妈再也不用担心文件打开失败了怎么办了。

在遍历文件中数据时,good()方法是个不错的选择,因为failed(),eof(),bad()在遍历时都有自己的奇葩之处(具体请百度,不做详解)。

0 0
原创粉丝点击