You should be using something like:
#include <stdio.h>
int main(void)
{
int a;
int n = scanf("%d", &a);
if (n != 1)
{
fprintf(stderr, "Failed to read an integer (%d)\n", n);
return 1;
}
printf("%d\n", a);
return 0;
}
The variable n
allows you to distinguish between EOF (usually -1
) and "the first data after white space was not part of an integer" (n
will contain 0
).
Note that the error message is printed on standard error; that's what it is for. You should normally print a newline at the end of output messages.
You could decide not to use n
and then not print it in the error message:
#include <stdio.h>
int main(void)
{
int a;
if (scanf("%d", &a) != 1)
{
fprintf(stderr, "Failed to read an integer\n");
return 1;
}
printf("%d\n", a);
return 0;
}
It is still important to test the result from scanf()
so that if the user typed zero
instead of 0
, you could spot the problem.
Note that a
would not be assigned if the matching fails — so without the test, you'd be printing an uninitialized variable, which is not a good idea. You could define int a = 0;
which would avoid that problem (with any choice of int
initializer that you like).