#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表格: