gpt4 book ai didi

c - 如何从c中的文件中读取特定值

转载 作者:太空宇宙 更新时间:2023-11-04 00:06:05 26 4
gpt4 key购买 nike

如果我有包含学生分数的文件例如这个文件

{ 
students scores :
100
90
83
70
}

如何在不读取“学生分数:”的情况下只读取分数的值???

mu代码已经ok了但是读取值的问题

这是我的代码

#include <stdio.h>

int main (void)
{
FILE *infile;
double score, sum=0, average;
int count=0, input_status;

infile = fopen("scores.txt", "r");
input_status = fscanf(infile, "%lf", &score);
while (input_status != EOF)
{
printf("%.2f\n ", score);
sum += score;
count++;
input_status = fscanf(infile, "%lf", &score);
}
average = sum / count;

printf("\nSum of the scores is %f\n", sum);
printf("Average score is %.2f\n", average);
fclose(infile);
getch();
}

最佳答案

我看到的问题:

input_status = fscanf(infile, "%lf", &score);
while (input_status != EOF)

是不对的。如果读取不成功,fscanf 的返回值将为 0,如果读取成功,则为 1

更重要的是,您需要添加代码来跳过所有内容,直到您希望看到数字为止。

char line[100];
while ( fgets(line, 100, infile) != NULL )
{
// If the line containing "students scores :"
// is found, break from the while loop.
if (strstr(line, "students scores :") != NULL )
{
break;
}
}

然后,将读取数据的行的开头更改为:

input_status = fscanf(infile, "%lf", &score);
while (input_status == 1 )

关于c - 如何从c中的文件中读取特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23839971/

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