If we check scanf()
return value, it shows 0
#include <stdio.h>
int main(int argc, char **argv)
{
int n=0;
int retvalue=0;
retvalue = scanf("%d",&n);
printf("first scanf() return: %d\n", retvalue);
retvalue = scanf("%d", &n);
printf("seconf scanf() return: %d\n", retvalue);
return 0;
}
scanf() documents on opengroup website
these functions shall return the number of successfully matched and
assigned input items; this number can be zero in the event of an early
matching failure.
As you enter a character value, and scanf()
function set to mach/accept "%d"
(decimal number) it fails.
[Edit after comment]
If the first scanf()
doesn't match the format specification, then the input isn't consumed and remains in the input buffer.
In other words, the character that doesn't match remains in input buffer and second scanf()
use it as input similarly second one also fail.
Warning
fflush(stdin)
solve this kind of misbehavior, but don't use because of fflush()
on stdin cause Undefined behavior.
[Edit2]
In this case a getchar()
call will Consume remaining buffer in stdin
.
int n=0;
int retvalue=0;
retvalue = scanf("%d",&n);
printf("first scanf() return: %d\n", retvalue);
if(!retvalue)
getchar();
retvalue = scanf("%d", &n);
printf("seconf scanf() return: %d\n", retvalue);
if(!retvalue)
getchar();