在 while 循环中等待 C 中的 enter 键?

Wait for press enter in C inside a while loop?

我正在编写一个 C 程序,我需要等待用户按任意键才能继续。当我使用 getchar(); 时,它会等待按下 Enter 键。但是当我在 while 循环中使用它时,它不起作用。如何让我的代码等待按下任意键以继续循环?

这是我的代码示例。我正在使用 GNU/Linux.

#include <stdio.h>
#include<stdlib.h>
int main()
{
    int choice;
    while(1) {
        printf("1.Create Train\n");
        printf("2.Display Train\n");
        printf("3.Insert Bogie into Train\n");
        printf("4.Remove Bogie from Train\n");
        printf("5.Search Bogie into Train\n");
        printf("6.Reverse the Train\n");
        printf("7.Exit");
        printf("\nEnter Your choice : ");
        fflush(stdin);
        scanf("%d",&choice);

        switch(choice)
        {
            case 1:
                printf("Train Created.");
                break;
            case 2:
                printf("Train Displayed.");
                break;
            case 7:
                exit(1);
            default:
                printf("Invalid Input!!!\n");
        }

        printf("Press [Enter] key to continue.\n");
        getchar();
    }

    return 0;
}

您可以在这里找到为什么 fflush(stdin) 不起作用的答案:

How to clear input buffer in C?

http://c-faq.com/stdio/stdinflush.html

希望对您有所帮助。

getchar()会读取你输入选择后按下的输入键。 在这种情况下 Enter 键 ASCII 13 被 getchar()

读取

因此您需要清除输入缓冲区或者您可以使用其他替代方法。

备选方案 1: 使用 getchar() 两次

{
    getchar(); // This will store the enter key
    getchar(); //This will get the character you press..hence wait for the key press

}

如果此代码(带有额外的 fflush)

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int choice;
    while(1){
        printf("1.Create Train\n");
        // print other options
        printf("\nEnter Your choice : ");
        fflush(stdin);
        scanf("%d", &choice);
        // do something with choice
        // ...
        // ask for ENTER key
        printf("Press [Enter] key to continue.\n");
        fflush(stdin); // option ONE to clean stdin
        getchar(); // wait for ENTER
    }
    return 0;
}

无法正常工作。

试试这段代码(带循环):

#include <stdio.h>
#include <stdlib.h>
int main()
{
    int choice;
    while(1){
        printf("1.Create Train\n");
        // print other options
        printf("\nEnter Your choice : ");
        fflush(stdin);
        scanf("%d", &choice);
        // do something with choice
        // ...
        // ask for ENTER key
        printf("Press [Enter] key to continue.\n");
        while(getchar()!='\n'); // option TWO to clean stdin
        getchar(); // wait for ENTER
    }
    return 0;
}