Consider the following simple C program.
//C test
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add\n");
scanf("%d%d",&a,&b);
c = a + b;
printf("Sum of entered numbers = %d\n",c);
return 0;
}
How do you check the values entered are actually two integers in some sensible range? Currently, if you just enter "a" and then return you get the output "Sum of entered numbers = 32767".
Examples of incorrect input I would like to prevent.
- 2 3 4 (wrong number of numbers)
- apple (not a number)
- 11111111111111111111111111 1111111111111111111111111111111111111 (numbers out of range)
Or should I be using fgets
and sscanf
or even strtol
?