Attendez appuyez sur enter en C dans une boucle while?

J’écris un programme C et je dois attendre que l’utilisateur appuie sur une touche pour continuer. Quand j’utilise getchar(); il attend que la touche Entrée soit enfoncée. Mais quand je l’utilise dans une boucle while, cela ne fonctionne pas. Comment faire en sorte que mon code attende qu’une touche soit enfoncée pour continuer la boucle?

Voici mon exemple de code. J’utilise GNU / Linux.

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

    Si ce code (avec fflush supplémentaire)

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

    ne fonctionne pas correctement.

    Essayez ce code (avec boucle):

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

    Votre réponse pourquoi fflush (stdin) ne fonctionnera pas, vous pouvez trouver ici:

    Comment effacer le tampon d’entrée en C?

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

    J’espère que cela t’aides.

    getchar() lira la touche de saisie que vous avez appuyée après avoir entré votre choix. Dans ce cas, la touche Entrée ASCII 13 est lue par getchar()

    Vous devez donc vider le tampon d’entrée ou vous pouvez utiliser d’autres alternatives.

    Alternative 1: utilisez getchar() deux fois

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