Validate Input to a C Program
Solution 1:
Besides the other interesting suggestions (especially the one with scanf
), you might also want to use the isdigit function:
The isdigit() function shall test whether c is a character of class digit in the program's current locale
note that this function examines only ONE char, not an entire bunch of them.
It is always good practice to resort to already-built functions; there are intricacies you might not be aware of even in the simplest task, and this will make you a good programmer overall.
Of course, in due time you might want to look at how that function works to get a good grasp of the underlying logic.
Solution 2:
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.