C++读取CSV表格(字符串型数据)



#include<stdio.h>
#include <string>
#include <iostream>
using namespace std;
#define ROWS 15
#define COLS 6
FILE*fp;
int main(void)
{
	errno_t err;
	char path[] = "D:/AllElectronics.csv";
	err = fopen_s(&fp, path, "r");
	if (err == 0)
	{
		printf("The file %s' was opened\n\n", path);
	}
	else
	{
		printf("The file %s' was not opened\n\n", path);
	}
	char tmpc;
	string tmps;
	string arr[ROWS][COLS];
	int ret = 1;
	int i = 0, j = 0;

	while (ret != EOF && i < ROWS)
	{
		ret = fscanf(fp, "%c", &tmpc);

		if (tmpc == '\n')
		{
			arr[i][j] = tmps;
			tmps = "";
			i = i + 1;
			j = 0;
		}
		else if (tmpc == ',')
		{
			arr[i][j] = tmps;
			tmps = "";
			j = j + 1;
		}
		else
		{
			tmps = tmps + tmpc;
		}
		cout << tmpc;

	}


	cout << "\naccess elements in arr:\n";
	for (int i = 0; i < 15; i++)
	{
		for (int j = 0; j < 6; j++)
		{
			cout << arr[i][j] << "  ";
		}
		cout << endl;
	}

	err = fclose(fp);


}




运行结果:

The file D:/AllElectronics.csv' was opened

RID,age,income,student,credit_rating,class_buys_computer
1,youth,high,no,fair,no
2,youth,high,no,excellent,no
3,middle_aged,high,no,fair,yes
4,senior,medium,no,fair,yes
5,senior,low,yes,fair,yes
6,senior,low,yes,excellent,no
7,middle_aged,low,yes,excellent,yes
8,youth,medium,no,fair,no
9,youth,low,yes,fair,yes
10,senior,medium,yes,fair,yes
11,youth,medium,yes,excellent,yes
12,middle_aged,medium,no,excellent,yes
13,middle_aged,high,yes,fair,yes
14,senior,medium,no,excellent,no

access elements in arr:
RID  age  income  student  credit_rating  class_buys_computer  
1  youth  high  no  fair  no  
2  youth  high  no  excellent  no  
3  middle_aged  high  no  fair  yes  
4  senior  medium  no  fair  yes  
5  senior  low  yes  fair  yes  
6  senior  low  yes  excellent  no  
7  middle_aged  low  yes  excellent  yes  
8  youth  medium  no  fair  no  
9  youth  low  yes  fair  yes  
10  senior  medium  yes  fair  yes  
11  youth  medium  yes  excellent  yes  
12  middle_aged  medium  no  excellent  yes  
13  middle_aged  high  yes  fair  yes  
14  senior  medium  no  excellent  no  



CSV表格:





  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值