Amirul Amirul - 1 year ago 85
C Question

Having problems with creating menu in C using do..while and if..else statement

I am new in this world of programming. I am learning programming at my school. My teacher recently ask the class to create a menu with limited selection that will end with a sentinel value.
So here's my coding:

#include <stdio.h>

void menu(void);
void choice1();
void choice2();
void choice3();
char choice;

int main() {
do {
if (choice =='1')
else if (choice =='2')
else if (choice =='3')
else if (choice =='4')
printf("Invalid character.");
} while (choice != '4');
return 0;

void menu(void) {
printf("1) Choice 1.\n");
printf("2) Choice 2.\n");
printf("3) Choice 3.\n");
printf("Choose any of the above, or enter 4 to quit.\n\n");
scanf("%c", &choice);

void choice1() {
printf("\nChoice 1\n");

void choice2() {
printf("\nChoice 2\n");

void choice3() {
printf("\nChoice 3\n");

When I try to run it, by putting the number
, the output came out but after that the function
and also the line "Invalid character." came out. As for as the other character, the
and the "Invalid character" came out twice. Number
does end the program. Is there any improvement that I can make to make sure the
and the line "Invalid character." does not come out unnecessarily?

Answer Source

In line-buffered input, the newline character lingers in the buffer after you read a single character for 'choice' and hence you get Invalid character. unintentionally.

You are required clear the buffer after reading the choice

scanf("%c", &choice);
/* Wasting the buffer
 * Hence ensuring that the character you enter
 * is indeed considered for 'choice'
  ;; // Do nothing in particular

As a side note, your program looks like a typical use-case for the switch-case command and maybe your teacher expects you to use it.

Considering the scenario mentioned by @chqrlie in [ this ] comment, the workaround is to add after

scanf("%c", &choice);

the below lines

int c;
while ((c = getchar()) != EOF && c != '\n') 
    ;; //Wasting the buffer
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download