跳过一些scanf介于两者之间

在这个程序中,第二个和第四个scanf跳过,不知道原因。 有人可以告诉原因吗?

#include main() { int age; char sex,status,city; printf("Enter the persons age \n"); scanf("\n%d",&age); printf("enter the gender\n"); scanf("%c",&sex); printf("enter the health status"); scanf("%c",&status); printf("where the person stay city or village"); scanf("%c",&city); if(((age>25)&&(age25&&age25&&age<35&&sex=='m'&&status=='b'&&city=='v') printf("60"); else printf("no"); } 

使用scanf()读取字符时,它会在输入缓冲区中留下换行符。

变化:

  scanf("%c",&sex); printf("enter the health status"); scanf("%c",&status); printf("where the person stay city or village"); scanf("%c",&city); 

至:

  scanf(" %c",&sex); printf("enter the health status"); scanf(" %c",&status); printf("where the person stay city or village"); scanf(" %c",&city); 

注意scanf格式字符串中的前导空格,它告诉scanf忽略空格。

或者,您可以使用getchar()来使用换行符。

  scanf("%c",&sex); getchar(); printf("enter the health status"); scanf("%c",&status); getchar(); printf("where the person stay city or village"); scanf("%c",&city); getchar(); 

我总是遇到与使用scanf相同的问题,因此,我使用字符串代替。 我会用:

 #include main() { int age; char sex[3],status[3],city[3]; printf("Enter the persons age \n"); scanf("\n%d",&age); printf("enter the gender\n"); gets(sex); printf("enter the health status"); gets(status); printf("where the person stay city or village"); gets(city); if(((age>25)&&(age<35))&&(sex[0]=='m')&&(status[0]=='g')&&(city[0]=='c')) printf("42"); else if(age>25&&age<35&&sex[0]=='f'&&status[0]=='g'&&city[0]=='c') printf("31"); else if(age>25&&age<35&&sex[0]=='m'&&status[0]=='b'&&city[0]=='v') printf("60"); else printf("no"); } 

如果第一个scanf仍然给你带来问题(跳过第二个问题, gets ),你可以使用一个小技巧,但你必须包含一个新的库

 #include ... char age[4]; ... gets(age); ... if(((atoi(age)>25)&&(atoi(age)<35))&&(sex[0]=='m')&&(status[0]=='g')&&(city[0]=='c')) 

并且每次使用age时都使用atoi ,因为atoi将char字符串转换为整数(int)。