欢迎来到IT嘟嘟的博客

人生三从境界:昨夜西风凋碧树,独上高楼,望尽天涯路。 衣带渐宽终不悔,为伊消得人憔悴。 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。
扩大
缩小

c++读取文本文件

首选创建一个包含数字的文本文件。该文件命名1.txt

c++程序实现如下:

#include<iostream>
#include<fstream>//文件I/O支持
#include<cstdlib>//提供exit()
const int SIZE = 60;//限制变量
int main()
{
	using namespace std;
	char filename[SIZE];
	ifstream inFile;//对象输入
	cout << "enter name of data file";
	cin.getline(filename, SIZE);
	inFile.open(filename);//关联文件
	if (!inFile.good())//是否打开文件
	{
	    cout << "could not open the file" << filename << endl;
		cout << "program terminating.\n";
		exit(EXIT_FAILURE);

		}
		double value;
		double sum = 0.0;
		int count = 0;//读入的数
		inFile >> value;//取第一个值
		while (inFile.good())

		{
			++count;
		   sum += value;
		   inFile >> value;

		}
		if (inFile.eof())
			cout << "end of flie reached.\n";
		else if (inFile.fail())
			cout << "input .\n";
		else
			cout << "input .\n";
		if (count == 0)
			cout << "no data processed.\n";
		else 
		{
			cout << "item ream:" << count << endl;
			cout << "sum: " << sum << endl;
			cout << "average" << sum / count << endl;

		}
		inFile.close();
		system("pause");
		return 0;
		
}

  

运行结果:

 

posted on 2018-10-14 14:46  IT嘟嘟  阅读(903)  评论(0编辑  收藏  举报

导航