接受C语言单个字符的菜单

接受C语言单个字符的菜单

本文介绍了接受C语言单个字符的菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在C程序中创建一个接受单个字符的简单菜单.菜单将如下所示:

I want to create a simple menu in C program that accepts single character. The menu will be like this:

  1. [S]如何
  2. [E] xit

如果用户输入"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 inputelse if the user enters '2',E or 'E' the program ends.else it should print "invalid input" and prompt again.

我能够创建该程序,但是问题是,当用户以1开头输入12、13、14、15、16 ......时,它显示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("\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');

}

推荐答案

您可以使用 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语言单个字符的菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 11:54