tags:

views:

401

answers:

3

What's the best way to get user input in a C program where the choices are of a limited number.

Say for example the choices are:

A) Print the list.
B) Add 99 to the end of the list.
C) Delete all duplicates.
5) Reset 5 times.

Entering "A" then enter is ok, Or, just a single keystroke would work as well.

A: 

I have used something simple like the following:

int intput()
{
char input = 0;
int ret_val = 0;

read(0, &input, 1);

switch(input) {
case 'c':
 // do c
    break;
case 'p':
 // do p
    break;
case 'd':
 // do d
    break;
case 'q':
 quit = 1;
    break;
case '?':
    PRINT(ENABLE, "c - connect\n");
    PRINT(ENABLE, "p - ping\n");
    PRINT(ENABLE, "d - disconnect\n");
    PRINT(ENABLE, "q - quit\n");
    PRINT(ENABLE, "? - this message\n");
    break;
}

return 0;
}
David Bryson
A: 

Little addition,

instead of using

switch(input)

use...

switch (toupper(input)) { case 'A':

This will allow the user to enter 'a' or 'A' and saves you having to check for upper and lower case

Tim Ring
+1  A: 

getchar(), or cgetc(), depending on the platform

dmityugov