Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12111

Multiple choice menu program in C using the switch statement and scanf () function

$
0
0

I'm trying to write a program with choice menu using the switch statement in C. Here's my code:

main (){    char option;    int test;    start:    printf ("Enter: ");    scanf ("%c", &option);    while (getchar() != '\n');    switch (option)        {            case '1':                 printf ("Test 1 : ");                scanf ("%d", &test);                break;            case '2':                printf ("Test 2 : ");                break;        }    if (option != 'q') goto start;}

The program is intended to repeat until 'q' character is inputted from the keyboard. The problem is whenever I try to input '1' from the keyboard for the first time (which executed the case 1), the next time I input '1' or '2' the program will skip case 1 (or 2) and go directly to the next loop, however after the next loop it executed the case 1 (or 2) normally. Besides, the case 2 (which don't have the scanf () function) everthing work correctly. I have also tried to remove the scanf from the case 1 and after that case 1 executed normally. Here're some of the output:

Enter: 1Test 1 : 5Enter: 1Enter: 1Test 1 : 7Enter: 2Enter: 2Test 2 :Enter: 2Test 2 :

Can anyone explain to me what's wrong with my code and tell me how to fix it?


Viewing all articles
Browse latest Browse all 12111

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>