c++读取.txt文件、.csv文件(vs2019)

直接上代码

#include <iostream>
#include <fstream>
#include <string>
#pragma warning(disable:4996)
using namespace std;

//读取输出txt文件
void txtout()
{
	cout << "==============================" << endl;
	cout << "成功读取txt文件。" << endl;

	//创建二维数组分别存储int及string数据
	string str[25][4];//用来存放字符串数据
	int num[25][2] = { 0 };//用来存放整形数据

	ifstream myfile("data.txt");
	ofstream outfile("out.txt", ios::trunc);

	if (!myfile.is_open()){
		cout << "can not open this file" << endl;
	}
	//遍历读取数据
	for (int i = 0; i < 25; i++){
		int count = 2;
		for (int j = 0; j < 6; j++){
			if (j < 2){
				myfile >> num[i][j];
			}
			else{
				myfile >> str[i][j - count];
			}
		}
	}
	//输出加载的数据
	for (int i = 0; i < 25; i++){
		cout << num[i][0] << "    " << num[i][1] << "    "
			<< str[i][0] << "    " << str[i][1] << "    "
			<< str[i][2] << "    " << str[i][3] << endl;
	};
	//将数据写入out.txt文件中
	for (int i = 0; i < 25; i++){
		outfile << num[i][0] << "\t" << num[i][1] << "\t"<< str[i][0] << "\t" << str[i][1] << "\t"<< str[i][2] << "\t" << str[i][3] << endl;
	};
	myfile.close();
	outfile.close();
}

//读取输出csv文件
void csvout()
{
	cout << endl;
	cout << "=========================================" << endl;
	cout << "成功读取csv文件。" << endl;

	int a[10][5];//存放数据的二维数组
	FILE* file;
	if ((file = fopen("test.csv", "r")) == NULL) {
		printf("Can't open the file!\n");
		exit(0);
	}
	fseek(file, 3L, SEEK_SET);   // 从文件第二行开始读取
	for (int i = 0; i < 10; i++) {
		for (int j = 0; j < 5; j++){
			fscanf_s(file, "%d", &a[i][j]);
			fseek(file, 1L, SEEK_CUR);   /*fp指针从当前位置向后移动*/
		}
	}

	for (int i = 0; i < 10; i++) {
		cout << a[i][1] <<"\t"<< a[i][2]<<"\t" << a[i][3] << "\t" << a[i][4] << "\t" << a[i][5] << "\t" << endl;
	}
	cout << "=========================================" << endl;
}

int main()
{
	txtout();
	csvout();

	system("pause");
	return 0;
}

原始数据格式

 未完待续

编程小白,望各位大佬批评指正。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值