简体   繁体   中英

Unexpected output in file handling

My input file is this

1001
1001
1101
1109

I have the following code-

char line[4];    
while(fgets(line,5,input)!=NULL)
 {
   printf("%s",line);

 }

It gives me the correct output as follows-

1001
1001
1101
1109

But if I modify my code to this-

while(fgets(line,5,input)!=NULL)
 {
   printf("%s",line);
   for(i=0;i<4;i++)
    {
     int c=line[i]-'0';
     printf("% d   ",c);     
    }printf("\n");   
 }

I get strange answer now-

1001 1    0    0    1   

-38   -48    0    1   
1001 1    0    0    1   

-38   -48    0    1   
1101 1    1    0    1   

-38   -48    0    1   
1009 1    0    0    9   

-38   -48    0    9  

Why is this strange output coming in my second case??

Your char array has 4 elements, while you're trying to put 5 elements [considering the null terminator] into it.

This way, you're accessing out-of-bound memory which produces undefined behaviour.

Also, worthy to mention, fgets() reads and stores the newline . You need to take care of that yourself.

With:

int c=line[i]-'0';

you are converting only one digit to an int but you want to convert the whole digit string:

int c= 0;
char *cp= line;
while (isdigit(*cp)) c= c*10 + *cp++ - '0';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM