我正在尝试创建一个程序,要求用户选择他想玩的阶段,然后程序询问他是否想再次玩或不玩,并且出于某种原因,如果用户输入'y'-程序 self 重复,但不运行函数“stages”。
int main()
{
while (again == 'y')
{
getStage();
}
if (again == 'n')
{
printf("BYE BYE!");
}
system("PAUSE");
}
/*
Function "getStage"-
- gets a choice from the user about the stage he wants to play on
and checks if the choice is proper.
- Transfers the program to the "randCode" function to make secret code.
- Transfers the program to the "stages" function
*/
void getStage()
{
choice= 0;
do
{
printf("What stage would you like to choose? Choose Wisely: ");
scanf("%d", &choice);
fflush(stdin);
system("COLOR 07");
} while(choice < 1 || choice > 4);
randCode();
stages(choice);
printf("Whould you like to play again? (y / n): ");
scanf("%c", &again);
}
最佳答案
在您的getStage()
函数代码中,您需要更改
scanf("%c", &again);
至
scanf(" %c", &again);
^^ // note the space here
跳过输入缓冲区中存在的换行符。
详细来说,当您输入一个输入并按 ENTER 时,它会存储输入,后跟由 ENTER 键引起的换行符。
在下一次迭代中,输入缓冲区中存在的 newline
将用作下一个 %c
格式说明符的输入,这使得 scanf()
来跳过一个步骤。
也就是说,
fflush(stdin)
是 undefined behavior 。摆脱它。int main()
至少应为int main(void)
以符合标准。
关于c - 程序重复出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34818351/