我想在 C 程序中创建一个接受单个字符的简单菜单。菜单将是这样的:
- [S]how
- [E]xit
如果用户输入“1”、“s”或“S”,程序将打印“Hello”并再次提示输入
否则,如果用户输入“2”、E 或“E”,则程序结束。
否则它应该打印“无效输入”并再次提示。
我能够创建该程序,但问题是当用户输入 12、13、14、15、16.....所以从 1 开始时,它会显示 Hello,其他选项也相同。
我的代码是:
#include <stdio.h>
void clearBuffer();
int main() {
int i = 0;
char selection;
do
{
printf("\t1. [S]how\n");
printf("\t2. [E]xit\n");
printf("Enter your selection from the number or character noted above: ");
scanf("%s", &selection);
clearBuffer();
if (selection == '1' || selection == 's' || selection == 'S')
printf("Hello");
else if (selection == '2' || selection == 'E' || selection == 'x')
i = 0;
} while(i != 0);
}
void clearBuffer()
{
while(getchar() != '\n');
}
如果您只接收一个字符,请考虑将 scanf() 函数替换为获取字符()功能:
printf("Enter your selection from the number or character noted above: ");
selection = getchar();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)