C语言接受单字符的菜单

编程入门 行业动态 更新时间:2024-10-27 11:16:00
本文介绍了C语言接受单字符的菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

  • [S]如何
  • [E]退出
  • 如果用户输入'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语言接受单字符的菜单

    本文发布于:2023-10-19 19:28:21,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1508537.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:字符   菜单   语言

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!