关于检查输入不合法的问题,请大牛们赐教
一个程序的健壮性测试,用户随意输入值程序不出错就达到了目地。第一份代码是用字符串处理,可以完整的控制用户的所有输入不合法的情况。第二份代码是用输出流控制。但是不管怎么处理也没有字符串处理的好。比如输入1.0,+1,1+这些值的话还输会判定为合法的输入。因为scanf返回值会有0,和1。我想知道不用字符串能完整处理好输入数字的方式。假如一个结构体有int float double char,各种类型的话。都用字符串处理的话那好麻烦,而且全是char型感觉也不美观,那不然其他类型的常量还有啥用呢?请大牛赐教!!!
代码1:
程序代码:#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char str[100];
while(1)
{
gets(str);
if(strlen(str) ==1 && str[0] >= 49 && str[0] <= 57 && str[0] != '.')
{
printf("输入合法\n");
//putchar(str[0]);
int c = atoi(str);
printf("%d\n", c);
}
else
{
printf("input error! iNput again\n");
}
}
}
代码2:
程序代码:#include<stdio.h>
#include<stdlib.h>
int main()
{
int a, b, c;
while(1)
{
c = scanf("%d", &a);
printf("%d ", c);
if (c == 1 &&c != 0 )
{
printf("YES\n");
fflush(stdin);
}
else
{
fflush(stdin);
printf("error!\n");
continue;
}
}
}









