从C中的文件中读取行和列

问题描述 投票:0回答:2

我试图用我的C代码读取此输入txt文件:

4 3
1.4 4.6 1
1.6 6.65 1
7.8 1.45 0
7 -2 2

并将它们分成行和列,以便我可以排序。我试过这样做,但我不断得到奇怪的数字。

所以我尝试在从文件中读取行和列后打印出行和列,输出为零。我意识到我的代码没有正确地从我的文本文件中读取数字。我尝试了不同的方法来解决无济于事的问题。任何帮助或指示将受到高度赞赏。

 #include <stdio.h>
#include <string.h>
#include <stdbool.h> //for bool

int main(){

    setvbuf(stdout, NULL,_IONBF, 0);

int c;
FILE *file;
FILE *infile;
char filename[99];
char choice;
int rows, columns;


//while(choice == 'y' || choice == 'Y'){
    printf("%s", "Enter file name: ");
    fgets(filename, 99, stdin);
    char *p = strchr(filename, '\n'); // p will point to the newline in filename
    if(p) *p = 0; 
    file = fopen(filename, "r");

    if (file) {
        while ((c = getc(file)) != EOF)
            putchar(c);
        fclose(file);
    }
    else{
        puts("FILE NOT FOUND");
    }

    //read rows and columns from file
    printf("%s","\n");
    fscanf(file, "%d", &rows);
    fscanf(file, "%d", &columns);

    printf("%d", rows);
    printf("%d", columns);

}

c arrays file multidimensional-array io
2个回答
1
投票

Problem 1

int rows = 0;
int columns = 0;
float matrix[rows][columns];
float sumOfRows[rows];

是不正确的。

之后,matrixsumOfRows中的元素数量是固定的。如果您在程序中稍后更改rowscolumns的值,它们将不会更改。

在定义rowscolumns之前,您需要先读取matrixsumOfRows的值。

问题2

    fscanf(file, "%d", &matrix[rows][columns]);

    printf("%f",matrix[rows][columns]);

也不对。鉴于matrix的定义,使用matrix[rows][columns]是不对的。他们使用越界索引访问数组。请记住,给定一个大小为N的数组,有效指数是0N-1


这是解决问题的一种方法:

fscanf(file, "%d", &rows);     // Use %d, not %f
fscanf(file, "%d", &columns);  // Use %d, not %f

// Now define the arrays.
float matrix[rows][columns];
float sumOfRows[rows];

// Read the data of matrix
for (int i = 0; i < rows; ++i )
{
   for (int j = 0; j < columns; ++j )
   {
      fscanf(file, "%f", &matrix[i][j]);  // Use %f, not %d
   }
}

0
投票

你的问题(实际上,有两个问题)在if (file) {...块中。首先,使用循环读取文件中的所有字符。因此,在循环结束时,您也位于文件的末尾。对fscanf的任何进一步调用都会导致未定义的行为。

其次,如果文件没有打开,你打印一条消息(到错误的输出)仍然继续到fscanf部分,这肯定会导致未定义的行为。

解决方案:删除while循环并修复错误处理代码:

if(file) {
    // Nothing!
} else {
    perror(filename);
    return 1; // or return EXIT_FAILURE;
}
© www.soinside.com 2019 - 2024. All rights reserved.