免责声明:我是一个苦苦挣扎的初学者
我的任务是将输入的 txt 文件中的整数读入二维数组。当我使用 printf 调试/测试时,我的 fscanf 没有从文件中读取正确的值。我不明白为什么。
我的代码如下:
void makeArray(int scores[][COLS], FILE *ifp){
int i=0, j=0, num, numrows = 7, numcols = 14;
for(i = 0; i < numrows; ++i){
for(j = 0; j < numcols; ++j){
fscanf(ifp, "%d", &num);
num = scores[i][j];
}
}
}
int main(){
int scoreArray[ROWS][COLS];
int i=0, j=0;
FILE *ifp;
ifp = fopen("scores.txt", "r");
makeArray(scoreArray, ifp);
system("pause");
return 0;
}
最佳答案
您正在将 num
(您从文件中读取的内容)分配给数组 scores[i][j]
的值,这是向后执行的。以下代码将读取每个数字之间的任意数量的空格,直到到达文件末尾。
void makeArray(int scores[][COLS], FILE *ifp) {
int i=0, j=0, num, numrows = 7, numcols = 14, ch;
for (i=0; i < numrows; ++i) {
for (j=0; j < numcols; ++j) {
while (((ch = getc(ifp)) != EOF) && (ch == ' ')) // eat all spaces
if (ch == EOF) break; // end of file -> break
ungetc(ch, ifp);
if (fscanf("%d", &num) != 1) break;
scores[i][j] = num; // store the number
}
}
}
This Stack Overflow帖子更详细地介绍了这个问题。
关于c - fscanf 和二维整数数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552862/