while循环问题
#include<stdio.h>main()
{
int age;
while(1)
{
printf("请输入年龄:");
scanf("%d",&age);
if(age>=16 && age<=30){break;}
}
}
为什么我输入a后就会无限printf("请输入年龄:");
而不执行scanf("%d",&age);
?
root@~ #cat 1.c #include <stdio.h> int main (void) { char age[3]; int isnum (char s[]);//isnum判断输入的是不是数字字符 int str2int (char s[]);//将数字字符转换成整数 while(1) { printf ("Enter age:"); scanf ("%s",age); if(isnum(age)==1){ if(str2int(age)>=16&&str2int(age)<=30) { printf ("Out of rang!bey!\n"); break; } }else{ printf ("Illegal,input again\n"); } } return 0; } int isnum (char s[]) { int i=0; while(s[i]!='\0') { if(s[i]<'0'||s[i]>'9') { return -1; } i++; } return 1; } int str2int (char s[]) { int i,sum=0; for(i=0;s[i]!='\0';i++) { sum=sum*10+(s[i]-'0'); } return sum; } root@~ # 测试: root@~ #./1 Enter age:12 Enter age:16 Out of rang!bey! root@~ #./1 Enter age:qwe Illegal,input again Enter age:300 Enter age:34 Enter age:31 Enter age:29 Out of rang!bey! root@~ #