scanf
returns the number of items that it has successfully scanned. If you asked for two integers with %d%d
, and scanf
returns 2, then it successfully scanned both numbers. Any number less than two indicates that scanf
was unable to scan two numbers.
int main()
{
int a,b;
int result;
printf("Enter two numbers :");
result = scanf("%d%d",&a,&b);
if (result == 2)
{
printf("Number 1 is : %d \n Number 2 is : %d",a,b);
}
else if (result == 1)
{
// scanf only managed to scan something into "a", but not "b"
printf("Number 1 is : %d \n Number 2 is invalid.\n", a);
}
else if (result == 0)
{
// scanf could not scan any number at all, both "a" and "b" are invalid.
printf("scanf was not able to scan the input for numbers.");
}
}
One other value that scanf
may return is EOF
. It may return this if there is an error reading from the stream.
Also note that main
returns int
, but you have it declared with void
return.