c++打开txt文本数据并存入二维数组(自动计算行数)

11 篇文章 0 订阅

计算txt文本数据行数

    ifstream file;//定义读取文件流 
	infile.open("data.txt");//打开文件
	char c;
	int line= 0;
	while (file.get(c))
	{
		if (c == '\n')
			line++;
	}
	file.close();//读取完成之后关闭文件

打开文本数据


#include <iostream>
#include <vector>        //提供向量头文件
#include <algorithm>     // 算法头文件,提供迭代器
#include <fstream>       //提供文件头文件
#include <iomanip>       //C++输出精度控制需要

using namespace std;

void readline(const char* strPath, int &line)
{
	ifstream is(strPath);
	char c;
	while (is.get(c))
	{
		if (c == '\n')
			line++;
	}
	is.close();
	cout << "line=" << line << endl;

}
int main()
{
	vector<double> V;
	vector<double>::iterator it;

	const char * filename = "data.txt";
	ifstream file(filename);
	
	double d;
	while (file >> d)
	{
		V.push_back(d);//将数据压入堆栈
	}
	file.close();
	int line = 1;
	readline(filename, line);
	double aa[100][2];
	for (it = V.begin(); it != V.end(); )
	{
		for (int i = 0; i < line; i++)//定义行循环
		{
			for (int j = 0; j < 2; j++)//定义列循环
			{
				aa[i][j] = *it; 
				it++;

			}
		}break;
	}
	cout << aa[0][0] << "   " << aa[0][1] << setprecision(16) << endl;//检验
	cout << aa[1][0] << "   " << aa[1][1] << setprecision(16) << endl;
	cout << aa[2][0] << "   " << aa[2][1] << setprecision(16) << endl;
	cout << aa[3][0] << "   " << aa[3][1] << setprecision(16) << endl;
	cout << aa[4][0] << "   " << aa[4][1] << setprecision(16) << endl;
	cout << aa[5][0] << "   " << aa[5][1] << setprecision(16) << endl;
	cout << aa[6][0] << "   " << aa[6][1] << setprecision(16) << endl;
 
	return 0;
} 


结果
在这里插入图片描述

参考:https://blog.csdn.net/m0_38036750/article/details/83478602

  • 7
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值