[英]Weird loop while reading from a file in C
I'm writing a code in C to read matrixes (square matrix with 3 <= dim <= 9) from a .txt file and print it exactly how it is written. 我正在用C语言编写一个代码,以从.txt文件中读取矩阵(方阵3 <= dim <= 9)并打印出它的确切编写方式。 The file is arranged as follows:
该文件的安排如下:
5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
6
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
The first number indicates the size of the subsequent matrix. 第一个数字表示后续矩阵的大小。
I wrote the following code: 我写了以下代码:
int main () {
FILE *arquivo;
char A[9][9];
int N;
int i,j;
char temp;
arquivo = fopen("matrizes.txt", "r");
if (!arquivo) printf("Erro.\n");
while (fscanf(arquivo, "%d", &N) != EOF) {
printf("%d \n", N);
fgetc(arquivo);
for (i = 0; ((i < N) && (temp = fgetc(arquivo)) != '\n') ; i++) {
for (j = 0; j < N; j++) {
A[i][j] = temp;
}
}
for (i = 0; i < N; i++) {
for(j = 0; j<N; j++) {
printf("%c", A[i][j]);
}
puts(" ");
}
}
return 0;
}
The output is this 输出是这个
5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
6
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
6
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
6
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
6
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
6
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
6
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
XXXXXX
I honestly have no idea why this is happening. 老实说,我不知道为什么会这样。 I tried different conditions to stop the loop, bot none of them worked out.
我尝试了不同的条件来停止循环,但没有一个程序能解决。
If I change 如果我改变
while (fscanf(arquivo, "%d", &N) != EOF)
while(fscanf(arquivo,“%d”,&N)!= EOF)
into 进入
while (fscanf(arquivo, "%d", &N) == 1)
而(fscanf(arquivo,“%d”,&N)== 1)
the output is just 输出是
5
AAAAA
AAAAA
AAAAA
AAAAA
AAAAA
The value of the second loop scanf in this case is "0". 在这种情况下,第二个循环scanf的值为“ 0”。 How can I fix it and print exactly what is written on the file?
我该如何解决它并准确打印文件上写的内容?
By the way, I know there are other forms to print a .txt exactly how it is made, I mean, I don't need 2D arrays to do this. 顺便说一句,我知道还有其他形式可以精确打印.txt的格式,我的意思是,我不需要2D数组来执行此操作。 However, I will use this program to read several matrixes and do some tests with them (also I want to print them as well), so I really need to store the data in a matrix of characters.
但是,我将使用该程序读取多个矩阵并对它们进行一些测试(我也想将它们打印出来),因此我确实需要将数据存储在字符矩阵中。
The problem is here. 问题在这里。
for (i = 0; ((i < N) && (temp = fgetc(arquivo)) != '\n') ; i++) {
for (j = 0; j < N; j++) {
A[i][j] = temp;
}
}
The loop will exit once it sees a newline and start the while
loop again. 一旦看到换行符,循环将退出并再次开始
while
循环。
Instead you want to read N lines. 相反,您想读取N行。
for (i = 0; i < N; i++) {
for(j = 0; (temp = fgetc(arquivo)) != '\n'; j++ ) {
A[i][j] = temp;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.