0

as the title suggests, I've tried making a sort-of interactive menu in two ways: one with a loop and the other by making a recursive function. Either way yields the same behaviour, that is, it "takes" my first input as the one for when it should be asked upon calling.

To better explain it, here's the code:

#include <stdio.h>

void goback(int *flag)
{
    char selector;

    printf("Do you want to return to menu?\n1. Yes\n2. No\n");
    selector=getchar();
    printf("\n");

    switch(selector)
    {
        case '1':
            break;
        case '2':
            *flag=1;
            break;
        default:
            printf("Invalid input!\n\n");
            goback(flag);
    }

}
int main()
{
    char select;
    int flag=0;

    do
    {
        printf("Main menu\n\n");
        printf("1. A\n2. Exit\n\n");
        scanf("%c", &select);
        switch(select)
        {
            case '1':
            //execute code here and ask the user if they want to go back
            //to the main menu
                goback(&flag);
                break;
            case '2':
                break;
            default:
                printf("Invalid input option!\n\n");
        }
    }while(select!='2' && flag==0);

    return 0;
}

Either of the two functions will have as an ouput the message that is printed should the user input a non-valid option, followed by a second iteration of whichever; why it takes the prior input when it is called either function?

  • This is an easy trap to fall into. The second call to `scanf` picks up newline character. I am sure there is a duplicate in SO. – R Sahu Mar 19 '18 at 05:16
  • In that case pardon, I've come across some similar but not the ones I was looking for. Edit: In that case, what should be the proper way to avoid this? I was thinking of reading the newline character after executing what's inside the options. – SerendipitousBoredom Mar 19 '18 at 05:24
  • That's ok. It's not always easy to find a question in SO that addresses the problem you are having. – R Sahu Mar 19 '18 at 05:25
  • Hmm, after reading the post you linked to, would it work if instead I read the newline outside of the switch? – SerendipitousBoredom Mar 19 '18 at 05:37
  • Yes, that is correct. – R Sahu Mar 19 '18 at 05:45
  • Thanks! Lastly, is better to make this sort of menus with a loop or is fine if I do it recursively like in goback(int *flag)? – SerendipitousBoredom Mar 19 '18 at 05:52

0 Answers0