c - 如何用 C 制作交互式菜单?
问题描述
出于某种原因,我的程序将打印菜单(使用 ShowMenu 功能),然后结束程序。我尝试调试但没有出现问题。
#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;
}
}```
解决方案
您没有MenuSize
正确计算,MenuSize
在您的声明之后打印并自己查看并printf
返回打印的字符数,因此return printf("%s\n", MenuOptions[Input]);
无论如何对您的目的都没有用。
如果您在下面进行更改,这将涵盖您的大部分问题
int MenuSize = sizeof(MenuOptions);
到
int MenuSize = sizeof(MenuOptions) / sizeof(MenuOptions[0]);
和
return printf("%s\n", MenuOptions[Input]);
到
printf("%s\n", MenuOptions[Input]);