Amirul Amirul - 3 months ago 10
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 {
menu();
if (choice =='1')
choice1();
else if (choice =='2')
choice2();
else if (choice =='3')
choice3();
else if (choice =='4')
break;
else
printf("Invalid character.");
} while (choice != '4');
return 0;
}

void menu(void) {
printf("\nMenu:\n\n");
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
1
,
2
,
3
, the output came out but after that the function
menu()
and also the line "Invalid character." came out. As for as the other character, the
menu()
and the "Invalid character" came out twice. Number
4
does end the program. Is there any improvement that I can make to make sure the
menu()
and the line "Invalid character." does not come out unnecessarily?

Answer

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);
while(getchar()!='\n') 
/* 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