该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
貌似理解了,getchar()只是从键盘缓存里面读取字符,如果没有赋值语句的话,那么读取到的字符也没有存在内存中,那么执行conetinue之后,刚才读取到的字符就被丢弃了,那么也就只读取并且保存了首字符,用while循环就把后面的输入都清除了。
下面是程序:
#include
#include
int main(void)
{
char ch;
printf("Give me a letter of the alphabet,and Will give ");
printf("an animal name\nbeginning with that letter.\n");
printf("Please type in a letter;type # to end my cat.\n");
while ((ch = getchar()) != '#') //只要输入的字符不是#,就执行循环
{
if (ch == '\n') //如果字符是回车,则跳过剩余部分,重新执行循环,重新检查输入的字符
{
continue;
}
if (islower(ch)) //只识别小写字母
{
switch (ch) //switch语句开始
{
case 'a':
printf("argali,a wild sheep of Asia\n");
break;
case 'b':
printf("babirusa,a wild pig of Malay\n");
break;
case 'c':
printf("coati,racoonlike mammal\n");
break;
case 'd':
printf("desman,aquatic,molelike critter\n");
break;
case 'e':
printf("echidna,the spiny anteater\n");
break;
case 'f':
printf("fisher,brownish marten\n");
break;
default:
printf("That's a stumper!\n");
break;
} //switch语句结束
}
else
printf("I recognize only lowercase letters.\n");
while (getchar() != '\n')
{
continue; //跳过输入行的剩余部分
}
printf("please type another letter or a #.\n");
} //while循环结束
printf("Bye!\n");
return 0;
}