0

In my fgetc.in file I have 9 and in the fgetc.out it shows 41 instead of 9. I am confused what is wrong in my code but I guess it is smth wrong with EOF.

#include<stdio.h>


int main(){
    FILE *in = fopen("fgetc.in", "r");
    FILE *out = fopen("fgetc.out", "wt");

    char c;
    int a = 0;
    c = fgetc ( in );
    a = c - '0';
    while(c != EOF ){
        c = fgetc ( in );
        a = a * 10 + (c - '0');
    }
    fprintf(out, "%d" , a);

    fclose(in);
    fclose(out);
    return 0;
}
  • 1
    @RussBear The argument to `atoi()` is a string, not a single character. – Barmar Dec 23 '20 at 23:39
  • 2
    `c - '0'` is the correct way to convert a single digit to the corresponding integer. – Barmar Dec 23 '20 at 23:39
  • You're right, I confused `char c` with `char* c` actually. I've never seen `c - '0'` before, thanks. – Matteo Pinna Dec 23 '20 at 23:44
  • You probably have other characters (such as spaces or a newline) in your input file. You don't do anything to avoid them, so they end up going into your a value computation is if they were digits. – Chris Dodd Dec 23 '20 at 23:59

1 Answers1

1

You're testing the previous read character for EOF in the while condition. So after you read the last character in the file, you'll read another character and add it to a. That next character will be EOF, whose value is -1. So you'll calculate

a = 9 * 10 + (-1 - '0');

which is 41.

You need to check for EOF after reading the character but before using it.

Also, fgetc() returns int, not char, since char might not be able to hold the EOF value. You need to declare c as int.

#include<stdio.h>

int main(){
    FILE *in = fopen("fgetc.in", "r");
    FILE *out = fopen("fgetc.out", "wt");

    int c;
    int a = 0;
    while(1){
        c = fgetc ( in );
        if (c == EOF) {
            break;
        }
        a = a * 10 + (c - '0');
    }
    fprintf(out, "%d" , a);

    fclose(in);
    fclose(out);
    return 0;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612