如果我有文件包含学生分数 例如这个文件
{
students scores :
100
90
83
70
}
我怎样才能读出分数的值而没有阅读"学生分数:" ???
mu代码已经可以了 但是阅读价值的问题
这是我的代码
#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();
}
答案 0 :(得分:1)
我看到的问题:
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 )
答案 1 :(得分:0)
这是解析文件的一种相当简单的方法。
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main (void)
{
FILE *infile;
char lineBuf[255+1];
double score, sum=0, average;
int count=0;
int fieldsParsed;
infile = fopen("scores.txt", "r");
/** Read a line from the file. **/
while(fgets(lineBuf, sizeof(lineBuf), infile))
{
/** Is the first character of the line a digit? **/
if(!isdigit(*lineBuf))
continue; /* It is not a digit. Go get the next line. */
/** Convert the number string (in lineBuf) to an integer (score). **/
score=atof(lineBuf);
printf("fields[%d] %.2f\n ", fieldsParsed, score);
sum += score;
count++;
}
average = sum / count;
printf("\nSum of the scores is %f\n", sum);
printf("Average score is %.2f\n", average);
fclose(infile);
// getch(); Non-portable
return(0);
}
答案 2 :(得分:-1)
使用fseek()跳过前导字节到数字。