How could I generate an error message when e.g. 'a' is the input value?
#include <stdio.h>
int main ( void )
{
int a;
scanf ("%d" , & a) ;
// if a is not a number, then generate error
return 0 ;
}
How could I generate an error message when e.g. 'a' is the input value?
#include <stdio.h>
int main ( void )
{
int a;
scanf ("%d" , & a) ;
// if a is not a number, then generate error
return 0 ;
}
You want to make sure that scanf
actually correctly recognized an integer, so check the return value. The scanf
family of functions returns an integer representing the number of correctly parsed elements, so if you do scanf("%d", ...)
you should expect a return value of 1
in case of a valid integer:
int a;
if (scanf("%d", &a) != 1) {
// the value read was not an integer, the end of file was reached, or some other error occurred
} else {
// good
}
This is all you can do with scanf
, however note that this is sadly not enough to ensure that the scanned value is indeed the actual value entered by the user, and that it has not overflowed.
The only sane way in which you can do this in C is through first getting the input as a string, and then parsing it using strtol
or similar functions, which are able to correctly report parsing and overflow errors.