- ; .
. , scanf() :
printf("Pick an option: ");
fflush(stdout);
scanf("%d", &option);
switch(option)
{
case 0 : do_something(); break;
case 1 : do_something_else(); break;
...
default: bad_option(); break;
}
, %d , , , \n ( , , %c , , getchar()).
, - , %d getchar() scanf() %s %c.
The best option is to read all the input as character strings using fgets(), then analyze and validate as needed.
int getOption(const char *prompt, char *option)
{
char input[3];
int result = 0;
printf("%s: ", prompt);
fflush(stdout);
if (fgets(input, sizeof input, stdin))
{
char *newline = strchr(input, '\n');
if (!newline)
{
printf("Input string is too long and will be rejected\n");
while (!newline && fgets(input, sizeof input, stdin))
newline = strchr(input, '\n');
}
else
{
*option = input[0];
result = 1;
}
}
else
printf("Received error or EOF on read\n");
return result;
}
Yes, it is a lot of work to read in one silly menu, and that is a simple version. Welcome to the wonderful world of interactive input processing in C.
source
share