int x;
scanf("%d",&x);
printf("%d",x);
Input: . (just a period)
Output: 4096
Why does it output 4096 here. Here is what I am thinking: So the ASCII value of a period is 46. Upon input, it reads in x as the bit pattern for 46? And when it prints, does it print out four bytes at the memory location of x, so only the first byte is filled with the bit pattern corresponding to 46, and the rest is random stuff that makes up the 4096? But this is incorrect, because look what happens when I do this–
int x;
scanf("%d",&x);
printf("%c",x);
Input: . (period)
Output: (nothing)
Input: 46
Output: . (period)
Even more confusing is what is going on when I do this:
int x;
scanf("%c",&x);
printf("%d",x);
Input: . (period)
Output: 4142
Input: 46
Output: 4148
Input: 47
Output: 4148
You need to check the return value of scanf (it’s the count of successfully read values):
If the parsing failed, the value of x is not defined.
Once
scanfhas failed, further calls will also fail because the invalid input is not removed from the stream. Because of this it is not a good idea to usescanf.