Menu that accepts single character in C language

2019-04-13 07:38发布

问题:

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

  1. [S]how
  2. [E]xit

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.

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.

My code is:

#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');

}

回答1:

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.");
}

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.



回答2:

If you are going to receive only one character consider replacing the scanf() function for getchar() function:

printf("Enter your selection from the number or character noted above: "); 
selection = getchar();


回答3:

As already mentioned, you should use getchar() if you only want one character. If you still want to use scanf() for whatever reason you may have, the correct format is "%c", not "%s".

I would also suggest that if you are looking for a single character, the if block looks a little "busy" (read, awkward) ... a switch would be a cleaner, more elegant way to do it (IMHO).

/* something like this ... */
switch ( selection ) {
  case '1':
  case 's':
  case 'S':
    printf ( "Hello\n" );
    break;

  case '2':
  case 'e':
  case 'E':
    i = 0;
    break;
}

Other couple of things ... if you don't care about the case of the character being read (that is, 's' and 'S' will do the same thing), you can convert selection to uppercase before your if-block or switch-block using toupper(). Also, and this is just a style suggestion, don't use i for your exit flag. General practice is to use things like i and j for counters or indexes - you could use something like quit_now or user_done which would convey more precisely what the variable means.



标签: c menu