为什么getchar()在switch case和while循环中没有暂停?

时间:2017-05-04 21:44:01

标签: c

#include <stdio.h>
#include <stdlib.h>

main()
{
    int Q = 1;
    while(Q==1)
    { 
        system("clear");
        printf("MAIN MENU\n");
        printf("--------------------------------------\n");
        printf("1 - See all files\n");
        printf("2 - See all files with permission\n");
        printf("3 - VIM Editor\n");
        printf("4 - EXIT\n");

        fputs("Enter Choice : ",stdout);
        char ch = getchar();

        switch(ch)
        {
            case '1' : system("ls"); break;
            case '2' : system("ls -l"); break;
            case '3' : system("vi"); break;
            case '4' : Q=0; break;
            default  : puts("Wrong Choice.."); break;
        }

        fflush(stdin);

        fputs("PRESS ENTER TO CONTINUE...",stdout);
        getchar();
    }
}

getchar()不会暂停而只是清除屏幕并再次启动菜单。

这些问题的原因是什么? 我正在使用tutorialspoint codingground在线编译器。

2 个答案:

答案 0 :(得分:6)

如果您显示了意外字符,您可以自己识别问题:

default:   printf ("Unrecognized choice:  '%c' (%d)", ch, ch);  break;

在任何类似的情况下使用这都不是一个糟糕的技术。如果代码以某种方式获得意外输入,请说明并显示已知的内容。

答案 1 :(得分:-1)

这是因为fflush()并不总是刷新stdin,而且它不是清除缓冲区最安全的方法。尝试使用scanf(“%c”,&amp; yourcharvariable),否则你应该使用另一个getchar()来消耗你的第一个输入左边的'\ n'。

请尝试使用此代码:

#include <stdio.h>
#include <stdlib.h>

main()
{
    int Q = 1;
    while(Q==1)
    { 
        system("clear");
        printf("MAIN MENU\n");
        printf("--------------------------------------\n");
        printf("1 - See all files\n");
        printf("2 - See all files with permission\n");
        printf("3 - VIM Editor\n");
        printf("4 - EXIT\n");

        fputs("Enter Choice : ",stdout);
        char ch = getchar();

        switch(ch)
        {
            case '1' : system("ls"); break;
            case '2' : system("ls -l"); break;
            case '3' : system("vi"); break;
            case '4' : Q=0; break;
            default  : puts("Wrong Choice.."); break;
        }

        fflush(stdin); // This doesn't always work. 
        getchar(); // It consumes the '\n' left by your first getchar().
        fputs("PRESS ENTER TO CONTINUE...",stdout);
        getchar();
    }
}