int main(void)
{
char ch;
printf("give me a letter in the alphabet ,and i will give ");
printf("an animal name \n beginning with that letter.\n");
printf("please type a letter ; type # to end my act.\n");
while((ch = getchar()) != '#')
{
if ('\n' == ch)
continue ;
if (islower(ch)) // 只接受小写字母
switch(ch)
{
case 'a' :
printf("A\n");
break;
case 'b' :
printf("B\n");
break;
case 'c' :
printf("C\n");
break;
case 'd' :
printf("D\n");
break;
case 'e' :
printf("E\n");
break;
default://补集;
printf("sb!\n");
}
else
printf("i regonize only lowercase letters .\n");
while(getchar() != '\n')
continue;
printf("please type another letter or a #.\n");
}
printf("done!");
return 0;
}
想问一下这条代码
while(getchar() != '\n')
continue;
printf("please type another letter or a #.\n");
的部分,如果我将36行和37行换一下位置,那么程序就不会有printf的打印,为什么?
while(getchar() != '\n')
continue;
printf("please type another letter or a #.\n");
这段代码的意思是条件getchar() != '\n'成立则走continue
while循环结束执行printf,所以无论while的条件是否成立都会执行printf
这里的while循环由于没有大括号{},所以其作用域在其后一行,如果36行和37行换一下位置之后printf在while的作用域内,只有while的条件成立才会走printf
直接将36行的continue;去掉呢
while(getchar() != '\n') 循环结束条件是输入回车,其他输入字符都会被忽略。一直在循环中。
建议你单步调试一下,看看每一步进入的分支情况。36行和37行互换,那么while(getchar() != '\n')语句只能够管辖一条语句呀。那么在不满足情况下,printf("please type another letter or a #.\n");不执行,肯定没有打印。同时continue;语句就成为了外面while((ch = getchar()) != '#')内的语句了,如此就会使得while(getchar() != '\n')语句成为了非“\n”的死循环。就不会有打印。
里面的代码重新整理一下吧,逻辑有些混乱。