我正在尝试将包含整数的 .csv 文件解析为 C 中的二维数组,但我的程序无法正常工作,我不确定为什么。
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
2,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2
(上面包含的是我试图解析的.csv文件,它只是1和2的整数。)
我的计划:
#include <stdio.h>
#define ROWS 12
#define COLUMNS 12
int main () {
int array [LEVEL_ROWS] [LEVEL_COLUMNS];
FILE *file;
file = fopen("data.csv","r");
if (file == NULL)
{
printf("error opening file");
return 1;
}
for (int i = 0; i < COLUMNS; i++)
{
for(int j = 0; j < ROWS; j++)
{
if(fscanf(file,"%d,",&array[i][j] )!=1)
{
fprintf(stderr,"error reading from file\n");
fclose(file);
return 1;
}
}
}
fclose(file);
for(int i = 0; i < COLUMNS; i++)
{
for (int j =0; j < ROWS; j++)
{
printf("%d ", array[i][j]);
}
printf("\n");
}
return 0;
}
但是,我的程序打印 .csv 文件的内容完全错误,我不明白为什么
打印输出(与.csv文件的实际内容不同):
2 2 2 2 2 2 2 2 2 2 2
2 2 2 2 2 2 2 2 2 2 1
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 2 2 1 1 1
1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 2 2 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
1 1 2 2 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1
2 2 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 2 2
有什么错误的帮助和解释吗?谢谢!
#define COLUMNS 12
与文件中的列数不匹配。文件中有 20 列。LEVEL_ROWS
和 LEVEL_COLUMNS
根本没有定义。int array [LEVEL_ROWS][LEVEL_COLUMNS];
,但您将列值读入行,反之亦然。最后一行末尾的“缺失”,
COLUMNS
定义为 20 并交换行和列读取(和打印),效果会很好。示例:
#include <stdio.h>
#define ROWS (12)
#define COLUMNS (20)
int main(void) {
const char* filename = "data.csv";
FILE* file = fopen(filename, "r");
if(file == NULL) {
perror(filename);
return 1;
}
int array[ROWS][COLUMNS];
for(int row = 0; row < ROWS; row++) {
for(int col = 0; col < COLUMNS; col++) {
if(fscanf(file, "%d,", &array[row][col]) != 1) {
fprintf(stderr, "error reading from file\n");
fclose(file);
return 1;
}
}
}
fclose(file);
for(int row = 0; row < ROWS; row++) {
for(int col = 0; col < COLUMNS; col++) {
printf("%d ", array[row][col]);
}
putchar('\n');
}
}