io - difference between scanf("%c" , ..) and getchar() -


i think scanf("%c" , &addr); equal getchar() before test this:

#include<stdio.h>  int main() {     int i;     scanf("%c",&i);     printf("%d\n", i);     if(i == eof)         printf("eof int type , char input\n");     =getchar();     printf("%d\n", i);     if(i == eof)         printf("eof int type , char input\n"); } 

i got output when use "ctrl+d" twice:

-1217114112

-1

eof int type , char input

since eof -1 in int type ,i try use scanf("%d",&i); replace scanf("%c",&i) , same output.

i got confused. can explain me?

----------------------------------edit-----------------------------------------------

i want know behavior of scanf("%c",i) of ctrl+d , test:

#include<stdio.h>  int main() {     int i;     int j;     j = scanf("%c",&i);     printf("%c\n", i);     printf("%d\n", j);     if(i == eof)         printf("eof int type , char input");      =getchar();     printf("%d\n", i);     if(i == eof)         printf("eof int type , char input"); } 

output:

k                  // if scanf set 1 byte in , why here print 'k' ? -1 -1 eof int type , char input 

your comparison not set i involves undefined behavior (ub).

int i;            // value of scanf("%c",&i);   // @ most, 1 byte of set, remaining bytes still unknown. printf("%d\n", i);// printing 'i' value not determined. 

had tried

char ch; int y = scanf("%c",&ch); printf("%d\n", ch); if(ch == eof) 

you potentially make match though input not eof. had scanned in char value of 255, char take on 2s compliment 8-bit value of -1. comparison sign extend 8-bit -1 match int size , match -1.
(assumptions: 2s compliment integers, 8-bit byte, eof == -1, char signed).

the correct eof test is

int y = scanf("%c",&ch); if (y == eof) 

note: getchar() & scanf() return eof implies end-of-file or i/o error. subsequent check of ferror(stdin) distinguishes this.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -