在 while 循环中等待在 C 中按 Enter 键? [英] Wait for press enter in C inside a while loop?

查看:34
本文介绍了在 while 循环中等待在 C 中按 Enter 键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

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

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
");
        printf("2.Display Train
");
        printf("3.Insert Bogie into Train
");
        printf("4.Remove Bogie from Train
");
        printf("5.Search Bogie into Train
");
        printf("6.Reverse the Train
");
        printf("7.Exit");
        printf("
Enter 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!!!
");
        }

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

    return 0;
}

推荐答案

如果这个代码(有额外的 fflush)

If this code (with additional fflush)

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

无法正常工作.

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

Try this code (with loop):

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

这篇关于在 while 循环中等待在 C 中按 Enter 键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆