我尝试将文件中的网格读取到二维数组中。该程序编译没有任何错误。这是代码:
#include <stdio.h>
#include <stdlib.h>
FILE* openFile(FILE* file, char* name, char* mode) {
file = NULL;
file = fopen(name, mode);
if(file == NULL) {
printf("Could not open a file!\n");
exit(1);
} else {
printf("File was opened/created successfully!\n\n");
}
return file;
}
int main() {
FILE* file;
file = openFile(file, "a.txt", "r");
char c;
int x, row, column;
x = row = column = 0;
int array[2][2];
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
array[i][j] = 0;
}
}
while(!feof(file) && (c = fgetc(file))) {
if(c == '\n') {
row++;
}
if(c != '\n' && c!= '\r') {
x = atoi(&c);
if(array[row][column] == 0) {
array[row][column] = x;
printf("array[%d][%d] = %d\n", row, column, array[row][column]);
printf("row = %d\n", row);
printf("column = %d\n\n", column);
column++;
}
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < column; j++) {
printf("array[%d][%d] = %d\n", i, j, array[i][j]);
}
printf("\n");
}
fclose(file);
return 0;
}
txt 文件:
02
46
程序的输出:
File was opened/created successfully!
array[0][0] = 0
row = 0
column = 0
array[0][1] = 2
row = 0
column = 1
array[0][0] = 0
array[0][1] = 2
看起来它只读取第一行,然后 feof() 返回它已到达末尾。我访问了一些网站试图了解问题所在。
谁能解释一下我犯的错误在哪里并显示正确的解决方案?
最佳答案
更改行时您没有重置列号。文件中的第二行保存在 array[1][2] 和 array[1][3] 中,但不显示它。
while(!feof(file) && (c = fgetc(file))) {
if(c == '\n') {
row++;
column = 0;
}
这通常可以工作。
关于c - 如何在C中将文件中的网格读入二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38585425/