等待在循环中按C键进入?

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

这是我的代码示例。 我正在使用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; } 

如果这个代码(附加fflush)

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

不能正常工作。

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

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

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

如何在C中清除输入缓冲区?

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

希望这可以帮助。

输入您的选择后, getchar()将读取您按下的输入键。 在这种情况下, 输入密钥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 }