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..

Recommended Answers

All 2 Replies

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.

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))
{
    /* ... */
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.