我想在 C 程序中创建一个接受单个字符的简单菜单.菜单如下:
I want to create a simple menu in C program that accepts single character. The menu will be like this:
如果用户输入'1'、's'或'S',程序将打印Hello"并再次提示输入否则,如果用户输入2"、E 或E",则程序结束.否则它应该打印无效输入"并再次提示.
If the user enter '1','s' or 'S' the program will print "Hello" and prompt again for the input else if the user enters '2',E or 'E' the program ends. else it should print "invalid input" and prompt again.
我能够创建程序,但问题是当用户输入 12、13、14、15、16.....所以从 1 开始时,它会显示 Hello,其他选项也一样.
I am able to create the program but the problem is that when user enters 12, 13, 14, 15, 16.....so on starting with 1, it shows Hello and same for other options.
我的代码是:
#include <stdio.h> void clearBuffer(); int main() { int i = 0; char selection; do { printf(" 1. [S]how "); printf(" 2. [E]xit "); 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() != ' '); } 推荐答案你可以使用 strlen,它是标准 C 库的一部分,用于检查 scanf 返回的字符串的长度并拒绝超过一个字符的条目:
You could use strlen, which is part of the standard C library, to check the length of the string returned by scanf and reject entries longer than one character:
if (strlen(selection) > 1) { printf("Invalid selection."); }或者,我认为您可以使用 getchar() 只接受来自用户的单个字符,这意味着他们不必按 Enter.
Alternatively, I think you could use getchar() to accept just a single character from the user, which means they wouldn't have to press enter.
更多推荐
C语言接受单字符的菜单
发布评论