C
C
Chemodan2282020-02-19 17:36:46
C++ / C#
Chemodan228, 2020-02-19 17:36:46

Error while reading from file to C. What should I do?

#include <stdio.h>
#include <stdlib.h>
int main() {
    FILE *in;
    int temp,sum=0;
    if ((in=fopen("input.txt","r"))==NULL){
        puts("ERROR");
        return 1;
    }
    while(!feof(in)){
        fscanf(in,"%i",&temp);
        printf("%i ",temp);
    }
    fclose(in);

    return 0;
}
выводит:
12 13 45 1 12 1 1

input.txt:
12 13 45 1 12 1
Tell me why the last character is duplicated?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
C
CityCat4, 2020-02-19
@TopToster

Don't use this [beep] construct while(!feof())
. It's just a problem. Use fscanf() in a loop until it returns EOF.
Yes, I know that this is the case in the examples - I myself once wrote using the same examples and then cursed for a long time, not understanding why it didn’t work ...

M
Mercury13, 2020-02-19
@Mercury13

feof returns true when we tried to read and failed because the caret hit the end of the file. And not when the caret is neatly parked at the end of the file - and even more so when it is separated from the end by spaces.
Better read about scanf...

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

…and see how you can remake the loop condition.

V
Vasily Melnikov, 2020-02-19
@BacCM

1. It is worth checking what the fscanf reading function returns.
She obviously couldn't read the number from the stream.
In your file, after the last unit, there is something like returning a string, a space, or something like that.
2. Keep variables closer to the place of use for code cleanliness. temp immediately before fscanf and initialize with something else. Then at least in such cases there will be not the last value, but a "marker"

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question