c语言 判断输入越界

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!");
}
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2008-08-15
while(1)
{
scanf("%d",&i);
if(i<=1 || i>=4)
printf("错误,重新输入数字!");
else break;
}
第2个回答  2008-08-15
if(i<1||i>4)
printf("不合法,请重新输入");
第3个回答  2019-05-05
你可以检查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!");
}
}