How can I make an interactive menu with C?

Viewed 304

For some reason my program will print the menu (with the ShowMenu function) and then just end the program. I tried debbuging but no problem appeared.

#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <stdbool.h>

int main() {
    bool Again = true;
    char* MenuName = "Games";
    char* MenuOptions[] = {"Tetris", "Paintball", "Wakfu", "Dofus", "Pokemon", "Legend of Zelda", "Super Mario bros", "Metroman"};
    int MenuSize = sizeof(MenuOptions);
    int Input = MenuSize + 1;
    printf("This program will show an interactive menu\n"); //What it does
    ShowMenu(MenuName, MenuOptions, MenuSize, Again, Input);
    return 0;
}

void ShowMenu(char* MenuName, char* MenuOptions[], int MenuSize, bool Again, int Input){
    while (Again){
        printf("%s\n", MenuName);
        for (int i = 0; i < MenuSize; i++){
            printf("%d - %s\n", i, MenuOptions[i]);
        }
        MenuSelection(Input, MenuOptions, MenuSize, Again);
    }
}

void MenuSelection (int Input, char* MenuOptions[], int MenuSize, bool Again){
    printf("Please choose an option within the menu\n");
    scanf("%d", &Input);
    if (Input > 0 && Input < MenuSize){
        return printf("%s\n", MenuOptions[Input]);
        Again = false;
    }
}```
1 Answers

You are not calculating the MenuSize correctly, print the MenuSize after your statement and see for yourself and printf returns the number of characters printed, so return printf("%s\n", MenuOptions[Input]); is not useful for you in anyway for your purpose.

This will cover most of your question, if you change below

int MenuSize = sizeof(MenuOptions);

to

int MenuSize = sizeof(MenuOptions) / sizeof(MenuOptions[0]);

and

return printf("%s\n", MenuOptions[Input]);

to

printf("%s\n", MenuOptions[Input]);

Related