0

I have a data.txt file and need to read different numbers of integers into every line for further processing, and some maybe a blank line.

//data.txt
3 7 2 1 9
8

234 0 2 -1

And I use a program to read it.

int main() {
    FILE *fp=fopen("data.txt","r");
    char input;
    int temp;
    if(fp==NULL){
        perror("Cannot open file!\n");
        exit(1);
    }

    while(!feof(fp)){
        while(fscanf(fp,"%c",&input)==1){
            if(input==' '){
                printf(" ");
                continue;
            }
            else if(input=='\n') {
                printf("This line finished.\n");
                continue;
            }
            else if(input=='-'){
                fscanf(fp,"%c",&input);
                temp=-(int)(input-'0');
                printf("%d",temp);
                continue;
            }
            temp=(int)(input-'0');
            printf("|%d|",temp);
        }

    }
    fclose(fp);
    return 0;
}

And I get some weird results with -35 on every line.

|3| |7| |2| |1| |9||-35|This line finished.
|8||-35|This line finished.
|-35|This line finished.
|2||3||4| |0| |2| -1
Process finished with exit code 0

Does anyone know what's wrong with my program?

HetaXD
  • 23
  • 5
  • [Please see Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/q/5431941/2173917)" – Sourav Ghosh Apr 17 '20 at 11:26
  • 1
    You're on windows (or your input file was created there, or in windows mode for some reason) and your line-endings are `\r\n` is what I'd guess. `ord('\r') - ord('0')` s `-35` – Masklinn Apr 17 '20 at 11:30
  • 1
    What is `temp=-(int)(input-'0');` supposed to do? Subtract magic number 35 from magic number 48 (`'0'`) and you get magic number 13 (`'\n'`). Most likely the culprit is the extra `fscanf(fp,"%c",&input);` which doesn't make any sense. – Lundin Apr 17 '20 at 11:31

1 Answers1

1

temp=(int)(input-'0');

You are subtracting 48 ( ASCII 0 ) from whatever input you have and getting -35. That means your input is 13. Quick check to ASCII table shows that 13 is \r, namely carriage return.

I am guessing you are on a Windows platform. Windows uses \r\n for new lines, you are printing \r as -35 and when you come to \n, you print "This line finished".

aulven
  • 521
  • 3
  • 14