0

let say I got input.txt with following thing

Kelly // name of student
67 // Biology Score
89 // Chemistry score
Michelle
75
45
John
78
90

and I use this fscanf command to scanf all the file until EOF:

while ((fscanf (input, "%s %d %d", &studName, &bioScore, &cheScore) ) != EOF)

because the command seem quite long, is there other method to do this without using the feof function? it should be like this:

while(????)/for(???)
{
fscanf ("%s", &studName);
fscanf ("%d", &bioScore);
fscanf ("%d", &cheScore);
}

is there any other method that look like above (use 3 fscanf), to scan and read all the input from a file? because it look neat and tidy.

thank in advance..

3
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by Tom Gunn
0

EOF != feof()
The former is a constant, and the other is a function call.

Also, this would be better while ((fscanf (input, "%s %d %d", studName, &bioScore, &cheScore) ) == 3) That is, a positive assertion of success, not a negative assertion of only one possible failure.


I'm assuming studName is a char array, in which case the & in the fscanf for this field is unnecessary.

0

If your goal is neat and tidy code, you should be abstracting the records into a struct and using functions to do the dirty work:

typedef struct StudentScore
{
    char name[SIZE];
    int biology,
        chemistry;
}
StudentScore;
int GetScoreRecord(FILE* ifs, StudentScore* score)
{
    return fscanf(ifs, "%s %d %d", 
                  score->name, 
                  &score->biology, 
                  &score->chemistry) == 3;
}
while (GetScoreRecord(input, &score))
{
    /* ... */
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.