I am taking C programming course. I did not understand these codes.
#include <stdio.h>
int main()
{
int c;
int ival;
printf("type : ");
c = getchar();
scanf("%d", &ival);
printf("c = %d\n", c); //65
printf("ival = %d\n", ival); //127
return 0;
}
For example whenever I type Abc, I am getting c = 65; ival = 1. why ival is 1?
ival
is never initialized, so it can have any value. The reason is that, c
is receiving 'A'
(through getchar()
) and then scanf
fails to read a number (since the next character in the input, 'b'
, is not a decimal number), so it never touches ival
.
You can check the return value of scanf
to see if it fails or succeeds:
if (scanf("%d", &ival) != 1)
printf("you need to enter a number\n");
else
printf("entered: %d\n", ival);
Note that scanf
returns the number of items it successfully read and assigned. For example scanf("%d %f %c", ...)
would return 3 if all three items were correctly read.1
1Note that assigned means that ignored input (such as those with the assignment-suppresion modifier (*
)) doesn't count towards the return value of scanf
(C11, 7.21.6.2.10,16). Furthermore, %n
doesn't affect the return value of scanf
(C11, 7.21.6.2.12).