Difference between scanf ("% c", ..) and getchar ()
I always think scanf("%c" , &addr); equals getchar() before testing this:
#include<stdio.h> int main() { int i; scanf("%c",&i); printf("%d\n", i); if(i == EOF) printf("EOF int type and char input\n"); i =getchar(); printf("%d\n", i); if(i == EOF) printf("EOF int type and char input\n"); } I got the result when I used "Ctrl + D" twice:
-1217114112
one
Type EOF int and char input
Since EOF is -1 in int , I am also trying to use scanf("%d",&i); replace scanf("%c",&i) , just getting the same result.
I'm confused. Can anyone explain this to me?
---------------------------------- EDIT ------------ --- --------------------------------
I want to know the behavior of scanf("%c",i) Ctrl + D, I check:
#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 and char input"); i =getchar(); printf("%d\n", i); if(i == EOF) printf("EOF int type and char input"); } Output:
k // If the scanf set 1 byte in i , why here print 'k' ? -1 -1 EOF int type and char input Your comparison is not fully established by i , as it includes Undefined Behavior (UB).
int i; // the value of i could be anything scanf("%c",&i); // At most, only 1 byte of i is set, the remaining bytes are still unknown. printf("%d\n", i);// Your are printing 'i' whose value is not fully determined. If you tried
char ch; int y = scanf("%c",&ch); printf("%d\n", ch); if(ch == EOF) You could make a match even if the input was not EOF. If you were to scan to char with a value of 255, char would take the 8-bit value of the 2nd character -1. A comparison would mean an 8-bit extension of -1 to fit the size of an int , and you would have to match -1.
(Assumptions: integers of compliments 2, 8-bit byte, EOF == -1, char).
Correct EOF Test
int y = scanf("%c",&ch); if (y == EOF) Note: getchar() and scanf() return EOF implies an I / O error or . A subsequent ferror(stdin) check distinguishes this.
The first value is probably undefined behavior. You cannot rely on i that matters if scanf() does not return 1.
With scanf() in particular, you seem to confuse the scanned value (character conversion according to the format specifier in the first argument) with the return value of the function call.
With getchar() , of course, this difference does not exist, since it only has a return value.