首页 > 解决方案 > 从 .txt 文件中读取矩阵

问题描述

这对我来说有点难,因为我发现的教程并不是很有用,而且我在这里找到的答案很混乱......我有这个 .txt 文件:

1  5  4  7  8  9  6  5  4  7  8  9
4  8  7  5  2  6  9  8  5  4  4  7
3  3  2  5  9  9  7  4  5  6  9  8
1  7  3  6  5  4  7  8  5  1  4  2
9  5  1  2  3  5  7  8  4  6  5  5
4  5  9  6  8  2  3  4  8  1  6  3
8  4  5  3  2  0  1  2  6  9  8  7
0  2  3  5  4  8  9  5  1  5  6  5
1  2  0  4  5  9  3  5  7  1  9  4
4  8  9  5  6  7  8  4  9  1  5  2
6  3  5  9  8  4  2  3  5  6  7  8
3  0  2  9  4  0  5  8  9  7  3  1

我需要把它转换成

int matr[12][12];

如何构建我的代码以便将所有这些数字放入矩阵中?我知道我应该使用 fscanf 和指针,但我不断收到错误,例如

无法将参数 '1' 的 'const char*' 转换为 'FILE* {aka _iobuf*}' 到 'int fscanf(FILE*, const char*, ...)'

所以,请在这里给我一些亮光。

标签: cmatrix

解决方案


根据您提供的(少量)内容,我认为您的问题是fscanf()期望 aFILE *作为其第一个参数,但您将文件名提供为const char *.

您可以FILE *使用fopen().

FILE * fileptr = fopen("<name of file in double quotes>", "r"); // open file for reading
if (fileptr == NULL) /* do some error handling stuff */;
int i, j;
for (i = 0; i < 12; ++i)
    for (j = 0; j < 12; ++j)
        fscanf(fileptr, "%d", &matr[i][j]);
// Some important matrix stuff...
fclose(fileptr); // close your file when done

推荐阅读