Rafael Dias
Rafael Dias

Reputation: 83

fscanf inside a do-while not working

So, I'm having problem to read a file using a do-while loop:

#include <stdio.h>

int main(){

FILE* f = fopen("teste.txt", "r");
double i;

do{

fscanf(f, "%lf ", &i);
printf(" %.0lf", i);

} while (fscanf(f, "%lf", &i) != EOF);

return 0;

}

The file is ike that:

1 2 3 4 5

When i run the program, the output is:

1 3 5

Can anyone help me?

Upvotes: 1

Views: 182

Answers (2)

Ashwani
Ashwani

Reputation: 2052

It should be:

#include <stdio.h>

int main() {
    FILE* f = fopen("teste.txt", "r");
    double i;
    fscanf(f, "%lf ", &i);
    do {
        printf(" %.0lf", i);
    } while (fscanf(f, "%lf", &i) != EOF);
    return 0;
}

after fscanf(f, "%lf ", &i);, f contains 1. Now after fscanf(f, "%lf", &i) != EOF, f contains 2. You are not printing that 2 and after next fscanf(f, "%lf ", &i);, f will contain 3. In short you are calling fscanf twice in every loop and printf only once.

Upvotes: 0

M.M
M.M

Reputation: 141544

You are discarding the result of every second call to fscanf.

In the while condition you call fscanf and check for EOF but you do not use the value of i. Then the next statement is back up the top of the loop , doing another fscanf which reads the next value (and does not check for error).

Also, you have an infinite loop if the file contains any text which is not a valid double.

The loop should be:

while ( fscanf(f, "%lf", &i) == 1 )
{
    printf(" %.0f", i);
}

Upvotes: 7

Related Questions