我正在尝试用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;
}
但是,如果我尝试将其放入无限循环中以继续运行,就像我所说的那样,它永远不会处理输入,直到我退出程序。
最佳答案
这段代码应该适合你——它也适合我。请注意变量 command
使用 int
。
#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;
}
关于C 中的命令行菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16500004/