码迷,mamicode.com
首页 > 编程语言 > 详细

C++文本数据读取

时间:2014-12-26 13:02:56      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:

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

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 exit

const int SIZE = 60;
int main()
{
	using namespace std;
	char filename[SIZE];
	char ch;
	ifstream inFile;	// object for handing file input
	
	cout << "Enter name of data file: ";
	cin.getline(filename,SIZE);
	inFile.open(filename);	// associate inFile with a file
	
	if(!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 read
	inFile >> ch;
	while(inFile.good())	// while input good not at EOF
	{
		sum++;
		inFile >> ch;
	}
	cout << sum << " characters in " << filename << endl;
	inFile.close();		// done with the file
	return 0;
}

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

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

C++文本数据读取

标签:

原文地址:http://blog.csdn.net/wzqnls/article/details/42169989

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!