This question already has an answer here:
I have a program which accepts an integer from the user and uses this number in an addition operation.
The code which I am using to accept the number is this:
scanf("%d", &num);
How can I validate the input such that if the user enters a letter or a number with the decimal point, an error message is displayed on the screen?
You should use
scanf
return value. Fromman scanf
:So it may look like this:
Notice it doesn't work for "numbers with the decimal point". For this you should rather use parsing and
strtol
for instance. It may be a bit more complex.Read your input as text using either
scanf
with a%s
conversion specifier or by usingfgets
, then use thestrtol
library function to do the conversion: