gpt4 book ai didi

c - 我在 C 中的开关(在 while 循环内)在正常运行之前直接进入默认状态

转载 作者:行者123 更新时间:2023-12-04 02:44:12 25 4
gpt4 key购买 nike

这是有问题的 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,执行默认值,回到循环顶部并从那里正常运行。知道为什么吗?这只是我的第 3 周编程,所以非常感谢外行人的术语。

最佳答案

我认为这是 scanf 的问题,因为它首先读取输入 - 尝试 getchar() 或在 scanf 中添加一个空格字符,例如 "%c"

scanf (" %c", &response);  

关于c - 我在 C 中的开关(在 while 循环内)在正常运行之前直接进入默认状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19195752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com