#include<stdio.h>
int main()
{
int guess = 1;
char response;
printf("is your num %d?\n",guess);
while ((response = getchar())!= 'y')
{
if (response == 'n')
printf("well,is your num is %d?\n",++guess);
else
printf("only y or n.\n");
while (getchar() == '\n')
continue;
}
printf("I know I could do it\n");
return 0;
}
你这个continue其实不用加,直接这样就好了。因为你之前在第一次输入后,第一个回车被读入,continue跳过了此次循环进入内部while的下一次循环,当前等于回车符会继续进行一次getchar读入,把你下一次的y或者n读入了,此时跳出内部while循环,然后再大的while循环回车会被作为response读入,每次都是判断是否等于‘n’,所以一直输出only y or n.\n,去掉内部的while循环或者只用一个getchar()问题就解决了。
如果有帮助请点一下我回答右上方的采纳,谢谢!以后有什么问题可以互相交流。
#include<stdio.h>
int main()
{
int guess = 1;
char response;
printf("is your num %d?\n",guess);
while ((response = getchar())!= 'y')
{
if (response == 'n')
printf("well,is your num is %d?\n",++guess);
else
printf("only y or n.\n");
}
printf("I know I could do it\n");
return 0;
}
或者只用一次getchar()吃回车
#include<stdio.h>
int main()
{
int guess = 1;
char response;
while ((response = getchar())!= 'y')
{
printf("%c\n",response);
if (response == 'n')
printf("well,is your num is %d?\n",++guess);
else
printf("only y or n.\n");
getchar();
}
printf("I know I could do it\n");
return 0;
}
你这个continue跳过的是这个内部的while
你这个continue是结束while循环的当前循环,while循环还在继续,没有结束。