【发布时间】:2022-01-07 20:24:45
【问题描述】:
我正在尝试向用户显示一个菜单并允许他们从选项中进行选择。它在一个while循环中,因为它必须迭代直到选择选项“e”退出程序。如果用户输入不被接受的值,我将“默认”选项作为故障保护。无论我做什么,默认情况总是运行,并且菜单在代码初始运行后总是出现两次。 我尝试将“getchar()”更改为 scanf,它仍然会产生相同的重复输出。我也尝试过完全取消开关,但使用 if/then 语句得到了相同的结果。我已附上我的完整代码,感谢您的帮助!
#include <stdio.h>
#include <stdlib.h>
// function for the menu
char menu() {
printf("Please select from the following menu: \n");
// setting up the menu from here
printf("a. input the data files location \n");
printf("b. enter the time interval \n");
printf("c. process and display the US Life Expectancy Data \n");
printf("d. process and display the Statistics of All Data \n");
printf("e. exit the program \n");
}
char options(char choice) {
switch (choice) {
case 'a':
printf("choice a\n");
break;
case 'b':
printf("choice b\n");
break;
case 'c':
printf("choice c\n");
break;
case 'd':
printf("choice d\n");
break;
case 'e':
break;
default: // default when none of the cases are matched
printf("Invalid input\n");
break;
}
}
// main function
int main(void) {
char choice;
do {
menu();
while ((choice = getchar()) == "\n") {};
if (choice == EOF) {
exit(1);
}
options(choice);
} while (choice != 'e');
}
【问题讨论】:
-
欢迎来到 SO。你得到一些编译器警告吗?你应该把它们调到最大。
-
getchar返回int,而不是char。您不应使用全局变量choice。特别是当您将变量传递给option。 -
您没有
while循环,而是do while循环。调试的一些提示:每当您输入default大小写时,打印该值。为此使用%d,而不是%c。您可能会为每个输入找到一个额外的13。 -
您是否还可以修复应该采用参数的函数 options() 的签名,并激活更高级别的警告(-Wall)
-
您有不返回任何内容的非 void 函数。和空参数列表但提供参数。我建议重新阅读学习材料中有关函数的章节。
标签: c while-loop switch-statement case