我正在尝试使用我的 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];
不对。
之后,matrix
和 sumOfRows
中的元素数量就固定了。如果您稍后在程序中更改行
和列
的值,它们也不会改变。
在定义matrix
和sumOfRows
之前,您需要先读取rows
和columns
的值。
问题2
fscanf(file, "%d", &matrix[rows][columns]);
printf("%f",matrix[rows][columns]);
也不对。鉴于matrix
的定义,使用matrix[rows][columns]
是不正确的。他们使用越界索引访问数组。
请记住,给定大小为 N
的数组,有效索引为 0
到 N-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/