在下面给出的代码中,如果我按'y'一次它会重复,但它并没有要求下一个书重复(或按'y')。有人可以帮助为什么这个代码在一个循环后终止?
main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf("%c",&choice);
}while(choice=='y');
}
在下面给出的代码中,如果我按'y'一次它会重复,但它并没有要求下一个书重复(或按'y')。有人可以帮助为什么这个代码在一个循环后终止?
main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf("%c",&choice);
}while(choice=='y');
}
您应该在 scanf() 调用之后读出换行符。否则,下一次就会选择它,所以 while 循环就会出现。
#include<stdio.h>
int main()
{
char choice;
do
{
printf("Press y to continue the loop : ");
choice = getchar();
getchar();
}
while(choice=='y');
return 0;
}
那是因为标准输入被缓冲了。因此,您可能正在输入 a 的字符串,y
后跟一个\n
(换行符)。
因此,第一次迭代采用y
,但下一次迭代不需要您的任何输入,因为\n
是标准输入缓冲区中的下一个。但是您可以通过让 scanf 使用尾随空格来轻松解决此问题。
scanf("%c ",&choice);
注意:c 后面的空格"%c "
但是,如果输入以y
. 因此,您还应该检查scanf
. 例如
if( scanf("%c ",&choice) <= 0 )
choice = 'n';
在 scanf 格式字符串的第一个字符处,插入一个空格。这将在读取数据之前清除标准输入中的所有空白字符。
#include <stdio.h>
int main (void)
{
char choice;
do
{
printf("Press y to continue the loop : ");
scanf(" %c",&choice); // note the space
}while(choice=='y');
return 0;
}