c - 程序重复出现问题

标签 c char newline scanf format-specifiers

我正在尝试创建一个程序,要求用户选择他想玩的阶段,然后程序询问他是否想再次玩或不玩,并且出于某种原因,如果用户输入'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()跳过一个步骤。

也就是说,

  1. fflush(stdin)undefined behavior 。摆脱它。
  2. int main() 至少应为 int main(void) 以符合标准。

关于c - 程序重复出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34818351/

相关文章:

c - 如何像 nm 命令一样显示符号的类型?

c - & 后跟 * 运算符的行为

使用来自 C99 的库在 Windows 上使用 TCC 编译文件

c - 我试图使这段代码递归,但由于某种原因它不起作用

c - scanf 一次获取多个值

c - 为什么 strtok(line, "\n") **不** 用于去除 fgets() 留下的换行符

c++ - 对于有保证的单个字符,使用 `char` 还是 `string` 更好?

C++ 字符串/字符* 连接

java - 扫描仪 - 忽略文件末尾的新行

c++ - 从文本文件中检测空行