c - fscanf 和二维整数数组

标签 c arrays 2d

免责声明:我是一个苦苦挣扎的初学者

我的任务是将输入的 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/

相关文章:

sql - SQL 中的列变量数组

ios - 删除特定数组元素,等于字符串 - Swift

javascript - 如何在 JavaScript 中将 JSON 对象转换为字符串和数字数组

algorithm - 距离图的高效计算

c - 为什么 MapViewOfFile 返回一个无法使用的 RapidXML 指针?

c - C套接字编程中不兼容的指针类型转换警告

unity-game-engine - 相机正投影尺寸一定宽度

java - 如何让一列的内容向下滑动到我的 7x7 二维数组的底行?

c - 为什么我的信号处理程序不仅等待子进程?

c - printf 改变了我的输出