c - 用 C 从文件中读取行和列

标签 c arrays file multidimensional-array io

我正在尝试使用我的 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);

}

最佳答案

问题 1

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

不对。

之后,matrixsumOfRows 中的元素数量就固定了。如果您稍后在程序中更改的值,它们也不会改变。

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

问题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
   }
}

关于c - 用 C 从文件中读取行和列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49040009/

相关文章:

c - 链表创建

c++ - 可以使用 using 为数组键入别名吗?

Javascript 对象,返回包含嵌套数组中值的更新对象

python - 将文本文件附加到文本文件

python - 在 Python 中将文本文件读入二维数组

javascript - 从使用 $http 从服务器下载的原始文件创建 Blob 对象。

c - 如何在 Windows 10 上打开 Glade Interface Designer?

c - 如何将 malloc 分配给另一个结构内部的结构?

c - 如何打印链接列表中的重复项及其出现次数?

java - 如何计算字符串数组中字符串的重复次数