gpt4 book ai didi

C 将文件读入二维数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:20:38 28 4
gpt4 key购买 nike

我有一个名为 input1.txt 的文件,它是一个由数字和一些字母组​​成的矩阵。我正在尝试读取它并将其存储在一个二维数组中,以便每个字符都是 1 个单元格。这是我的文本文件:

1111S11110
0000010001
110100010d
t001111110
0100000001
0111111101
1111111101
00000D01T1
0111110001
0000E01110

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


// Function for finding the array length
int numOfLines(FILE *const mazeFile){
int c, count;
count = 0;
for( ;; ){
c = fgetc(mazeFile);
if( c == EOF || c == '\n' )
break;
++count;
}
return count;
}

// Main Function
int main( int argc, char **argv )
{
// Opening the Matrix File
FILE *mazeFile;
mazeFile = fopen( "input1.txt", "r" );
if( mazeFile == NULL )
return 1;
int matrixSize = numOfLines( mazeFile );

// Reading text file into 2D array
int i,j;
char mazeArray [matrixSize][matrixSize];

for(i=0;i<matrixSize;i++){
for(j=0;j<matrixSize;j++){
fscanf(mazeFile,"%c", &mazeArray[i][j]);
}
}

for(i=0;i<matrixSize;i++){
for(j=0;j<matrixSize;j++){
printf("%c",mazeArray[i][j]);
}
}

fclose( mazeFile );
return 0;
}

然而,当我打印它们时,我的控制台输出是这样的:

0000010001
110100010d
t001111110
0100000001
0111111101
1111111101
00000D01T1
0111110001
0000E01110@

似乎它没有读取第一行,但是就索引而言,我认为还可以。我是 C 的新手。有人可以帮忙吗。提前致谢。

最佳答案

这里有几个问题:

numOfLines 函数错误。这是更正后的版本;它实际上计算行数并将文件指针重置为文件的开头。

您的版本只计算了第一行中的字符数(恰好是 10,因此该值似乎是正确的),并且它没有将文件指针重置为文件的开头(因此第一行是在你的输出中丢失)。

int numOfLines(FILE *mazeFile) {  // no const here BTW !!
int c, count;
count = 0;
for (;; ) {
c = fgetc(mazeFile);
if (c == EOF)
break; // enf of file => we quit

if (c == '\n')
++count; // end of line => increment line counter
}
rewind(mazeFile);

return count+1;
}

然后你忘记吸收每行末尾的 \n 字符。此 \n 位于文件每一行的末尾,但您需要阅读它,即使您不想将它存储在二维数组中也是如此。

  for (i = 0; i<matrixSize; i++) {
for (j = 0; j<matrixSize; j++) {
fscanf(mazeFile, "%c", &mazeArray[i][j]);
}

char eol; // dummy variable
fscanf(mazeFile, "%c", &eol); // read \n character
}

最后,由于上述原因,您需要打印 \n

for (i = 0; i<matrixSize; i++) {
for (j = 0; j<matrixSize; j++) {
printf("%c", mazeArray[i][j]);
}

putc('\n', stdout); // print \n
}

关于C 将文件读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46793200/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com