c语言 判断输入越界

来源:百度知道 编辑:UC知道 时间:2024/06/07 07:32:31
int i;
scanf("%d",&i);我想要得到i为大于1小于4的整数,如何判断用户输入的很长一个字符串如asggdssdeg,是不合法的,并要求重新输入

你可以检查scanf的返回值,如果不等于1说明输入是afsaf之类的字符串,这个时候scanf不会读入这些串,你后面要用fgets来读取来抛弃输入流的数据。

int i;
int result;
char buf[80];

while (1)
{
result = scanf("%d", &i);
if (result == 1 && i >= 1 && i <=4)
break;
else
{
/* 抛弃用户的输入 */
fgets(buf, 80, stdin);
printf("Error, Please Input again!");
}
}

while(1)
{
scanf("%d",&i);
if(i<=1 || i>=4)
printf("错误,重新输入数字!");
else break;
}

if(i<1||i>4)
printf("不合法,请重新输入");