你好,我是程序初学者。我有个简单的问题。当我接受用户输入时。我被要求进入你的年龄:进入年龄后,我被问到(问题在这里:为什么要执行两行)“输入c表示城市,v输入代表村庄:输入h表示健康,而'p‘表示健康:
光标出现在健康之后:
它应该要求“输入c代表城市,v代表村庄:”第一。我试过很多次。请帮帮我
int main(){
int age;
char sex;
char location;
char health;
printf("Enter Your Age: ");
scanf("%d",&age);
printf("Enter c for city and v for village: ");
scanf("%c", &location);
printf("Enter 'h' for healthy and 'p' for poor health: ");
scanf("%c", &health);
printf("Enter 'm' for male and 'f' for female: ");
scanf("%c", &sex);
if(age>=25 && age<=35){
printf("hello ahmed ");
}
else{
printf("Sorry You Cannot Be Insured ");
}
getch();
return 0;
}发布于 2014-03-02 13:17:54
似乎当你进入你的年龄,‘进入’仍然在缓冲区中,并被读取到位置。
printf("Enter Your Age: ");
scanf("%d",&age);
printf("Enter c for city and v for village: ");
scanf("\n%c", &location); // add this line to ignore the newline character.编辑:删除fflush(),因为它似乎只适用于输出流,而不是输入。海事组织最好是先读取newline字符,然后再读取实际的location字符。
发布于 2014-03-02 13:29:39
另一种选择是
scanf(" %c", &location);
在%c之前包含一个空格,以使其忽略空白或新行。
https://stackoverflow.com/questions/22127978
复制相似问题