下面是有问题的while循环和开关(track1定义了一个更大的循环,此处未显示):
while (track6 ==1)
{
printf ("would you like to play again? Y or N?\n");
scanf ("%c", &response);
switch (response)
{
case 'Y' : track6 = 2;
break;
case 'N' : printf ("thanks for playing!\n");
track6 = 2, track1 = 2;
break;
default : printf ("response is case-sensitive and must be either Y or N. your response is invalid. please reenter.\n");
}
}我收到的输出是:
would you like to play again? Y or N?
response is case-sensitive and must be either Y or N. your response is invalid. please reenter.
would you like to play again? Y or N?(提示输入,然后正确执行)
它似乎是在执行第一个printf,跳过scanf,执行默认值,回到循环的顶部,然后在那里正常运行。知道为什么吗?这只是我的第三个星期的节目,所以外行的条款受到赞赏。
发布于 2013-10-05 08:43:17
看起来它正在执行第一个
printf,跳过scanf,执行默认,回到循环的顶部,然后在那里正常运行。知道为什么吗?
不是的。看起来它正在执行第一个(**\n**)语句,读取前一个 scanf,留下的换行符,返回到循环的顶部,并在那里正常运行。一个可能的解决办法是改变这个换行符。
scanf ("%c", &response);至
scanf (" %c", &response);
^
|
add a space here to eat up '\n' 但是,如果并且只有当用户输入是Y或N时,这才能起作用。如果用户输入YES或NO,多个字符(不包括\n),那么您的程序必须吃掉所有这些额外字符才能正常运行程序。为此,在scanf in while之后使用一个循环;
printf ("would you like to play again? Y or N?\n");
scanf ("%c", &response);
while ((response = getchar()) != '\n' && response != EOF)
;发布于 2013-10-05 08:43:31
我认为这与scanf有关,因为它首先读取enter -尝试getchar()或在scanf中添加空格字符(如" %c" )
scanf (" %c", &response); 发布于 2013-10-05 08:44:56
使用
scanf ("%c", &response);您需要跳过以前的scanf中的尾换行符
因此,请使用:
int ch;
while ((ch = getchar()) != '\n' && ch != EOF); //eats '\n' scanf后
https://stackoverflow.com/questions/19195752
复制相似问题