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;
		
}

  

运行结果:

 

转载于:https://www.cnblogs.com/277223178dudu/p/9786334.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用C++中的文件流来读取文件内容。下面是一个简单的例子: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myfile("example.txt"); // 创建一个文件输入流对象并打开文件 string line; if (myfile.is_open()) { // 判断文件是否成功打开 while (getline(myfile, line)) { // 从文件中逐行读取内容 cout << line << endl; // 输出每一行的内容 } myfile.close(); // 关闭文件 } else { cout << "Unable to open file." << endl; } return 0; } ``` 上述代码将打开名为example.txt的文件,并逐行输出其内容。在代码中,我们使用了`ifstream`类来创建一个文件输入流对象。我们将文件名作为参数传递给构造函数,该构造函数将打开文件并返回一个可以用于读取文件内容的流对象。在代码的主循环中,我们使用`getline`函数逐行读取文件内容,并将其存储在一个字符串变量`line`中。最后,我们将每一行的内容输出到控制台中,并在循环结束后关闭文件流对象。 如果您想一次性读取整个文件的内容,可以使用以下代码: ```c++ #include <iostream> #include <fstream> #include <string> using namespace std; int main() { ifstream myfile("example.txt"); // 创建一个文件输入流对象并打开文件 string content; if (myfile.is_open()) { // 判断文件是否成功打开 // 获取文件长度 myfile.seekg(0, ios::end); int length = myfile.tellg(); myfile.seekg(0, ios::beg); // 分配足够的内存来存储文件内容 content.resize(length); // 从文件中读取内容 myfile.read(&content[0], length); myfile.close(); // 关闭文件 } else { cout << "Unable to open file." << endl; } cout << content << endl; // 输出文件的内容 return 0; } ``` 在上述代码中,我们首先创建了一个`ifstream`对象并打开了文件。然后,我们使用`seekg`和`tellg`函数获取文件长度,并分配足够的内存来存储文件内容。最后,我们使用`read`函数从文件中读取内容,并将其存储在字符串变量`content`中。最后,我们将整个文件的内容输出到控制台中,并在循环结束后关闭文件流对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值