Rafael Dias
Rafael Dias

Reputation: 83

fscanf loop not working properly

So, i have the following code:

#include <stdio.h>

int main() {
FILE* f = fopen("test.txt", "r");
FILE* p = fopen("test2.txt", "w+");
double i;
char j;

while (!feof(f)){

    fscanf(f, " %c", &j);

    if ((j == '(')||(j == ')'))
    fprintf(p, "%c ", j);
    else {
    ungetc(j,f);
    fscanf(f, "%lf ", &i);
    fprintf(p, "%.2lf ", i);
    }

}

return 0;
}

The file I'm reading (test.txt) is this:

13.3 3 (

and the file test2.txt is like that:

13.30 3.00 ( (

But the last parenthese shouldn't appear. Why this is getting the last char twice?

Upvotes: 0

Views: 135

Answers (1)

John Zwinck
John Zwinck

Reputation: 249113

You shouldn't check for feof() like that. Instead, simply check the result of fscanf():

while (fscanf(f, " %c", &j) == 1) {

Upvotes: 1

Related Questions