gpt4 book ai didi

c - 无法在 C 中正确读取文件

转载 作者:行者123 更新时间:2023-11-30 20:59:31 24 4
gpt4 key购买 nike

嘿,大家好,我是新来的,我正在编写一些旨在读取 2 个文件的代码。文件打开得很好,一切都在稍后分配好,但是,当我从文件中读取单独的行时,我遇到了问题。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int main()
{
char filename1[100];
//Seting the file name for entery and seting the limit to 100
//this one is for my matrix//
FILE* fp1;
//FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
//This will pull in the name entered by the user//
scanf("%s", filename1);
//scans in the name of the first file the file type needs to be
included//

fp1 = fopen(filename1, "r");
//This will open the file as entered by the user//
if (fp1 == NULL)
{
printf("\nError, file not found\n");
exit(0);
}
int i;
int row1;
int col1;

fscanf(fp1, "%d,", &row1);
printf("%d \n ", row1);
fscanf(fp1, "%d,", &col1); //WHY IS THIS SCANING WRONG!!!!//
printf("%d \n ", col1);
//This will scan for the number of rows and columns in the matrix//
//thats all for reading in the first file//

char filename2[100];
//Seting the file name for entery and seting the limit to 100//
FILE* fp2;
//FILE must be set as a pointer (FILE must also be capitalized)//

printf("Enter file name including file extention: \n");
//This will pull in the name entered by the user//
scanf("%s", filename2);
//Scans in the name of the first file//

fp2 = fopen(filename2, "r");
//This will open the file as entered by the user//
if (fp2 == NULL)
{
printf("\nError, file not found\n");
exit(0);
}
return 0;
}

这是我编译并运行完整程序时得到的结果。 compiling

加载数据文件后应该出现的是 5 和 3。
数据位于附图中,但也位于此处:

5
3
3.4, 6.5, 4.1
1.8, 3.3, 4.5
2.6, 7.4, 4.9
5.5, 6.1, 2.4
1.9, 2.7, 4.2

除此之外,我的代码中的其他所有内容都运行良好。

最佳答案

好的,根据您的输入,这是一个最小的工作代码

    int i, j;
int row1;
int col1;
float v;
fscanf(fp1, "%d\n", &row1);
fscanf(fp1, "%d\n", &col1);

for ( i = 0 ; i < row1; i ++ )
{
for( j = 0 ; j < col1; j ++ )
{
fscanf(fp1, "%f, ", &v);
}
}

关于c - 无法在 C 中正确读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47278715/

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