Search code examples
cwhile-loopkeypressgetchar

Wait for press enter in C inside a while loop?


I'm writing a C program and I need to wait for the user to press any key to continue. When I use getchar(); it waits for the Enter key to be pressed. But when I use it inside a while loop, it doesn't work. How can I make my code wait for any key to be pressed to continue the loop?

Here is my code sample. I am using 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;
}

Solution

  • If this code (with additional 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;
    }
    

    does not work properly.

    Try this code (with loop):

    #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;
    }