Consider the following simple C program.
//C test
#include<stdio.h>
int main()
{
int a, b, c;
printf("Enter two numbers to add
");
scanf("%d%d",&a,&b);
c = a + b;
printf("Sum of entered numbers = %d
",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
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…