【发布时间】:2018-09-04 06:30:59
【问题描述】:
我想从文件中读取矩阵并将其存储在一个数组中。但是数组只存储矩阵的最后一个值。谁能解释一下?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
FILE *fp, *fp1;
int n = 0, i, j, a[4][4], b[16];
fp = fopen("Output.txt", "r");
if (fp == NULL) {
printf("\nError; Cannot open file");
exit(1);
}
while (!feof(fp)) {
i = 0;
fscanf(fp, "%d", &n);//reads the file containing matrix
b[i] = n;//this part is not working
printf("%d\n", n);
i++;
}
fclose(fp);
fp1 = fopen("Output2.txt", "w");
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
fprintf(fp1, "%d\t", a[i][j] * 2);
}
fprintf(fp1, "\n");//creates file of altered matrix
}
fclose(fp1);
return 0;
}
【问题讨论】:
-
在第一个 while 循环中,每次都将 i 重置为 0。
-
其次,请learn how to debug your program。尤其是一些简单的rubber-duck debugging 应该可以帮助您快速找到主要问题。
-
嗨!每次输入 while 时,都会将 0 分配给变量 i,因此
b[i]将始终为b[0]。试着把我放在你的时间之外 -
最后,你永远不会初始化
a!它的内容将是不确定的。
标签: c file-handling