-3

我正在尝试在 C 中实现一个命令行菜单,这样当用户输入一个字符时,它会立即处理该字符并执行特定的功能。问题是,每当我尝试让它在处理每个输入后,菜单再次显示并准备好接受新输入时,程序将不断读取输入并且永远不会处理它,除非我退出程序。

这是通过 1 次工作的代码:

char command;
    command = getchar();
    switch(command){
    case 'c':
        //create a new hash table;
        break;

    case 'l':
        //look up a word;
        break;

    case 'f':
        //read a file
        break;

    case 'p':
        //print the table;
        break;

    case 'r':
        //Remove a word
        break;

    case 'q':
        exit(0);
        break;
    }

但是,如果我尝试将它放入无限循环以继续运行,就像我说的那样,它永远不会处理输入,直到我退出程序。

4

1 回答 1

0

这段代码应该对你有用——它对我有用。注意int变量的使用command

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

int main(void)
{
    int command;

    while ((command = getchar()) != EOF)
    {
        switch(command)
        {
        case 'c':
            printf("Create a new hash table\n");
            break;

        case 'l':
            printf("Look up a word\n");
            break;

        case 'f':
            printf("Read a file\n");
            break;

        case 'p':
            printf("Print the table\n");
            break;

        case 'r':
            printf("Remove a word\n");
            break;

        case 'q':
            printf("Quit\n");
            exit(0);
            break;

        default:
            printf("Unexpected input %d (0x%.2X) ('%c')\n",
                   command, command, isgraph(command) ? command : '.');
            break;
        }
    }
    return 0;
}
于 2013-05-11T19:16:22.450 回答