dapernia said:
Hi friends, I want to make menu in my C program
For example:
Main Menu: (1) Enter Data, (2) Control Variables (3) Exit
I want to make this menu to go through the options just pressing numbers
1,2 and 3.
Thanks Daniel
One method for menus is to use tables.
typedef void (*Ptr_To_Function)(void);
struct Menu_Record
{
unsigned int option_number;
const char * text;
Ptr_To_Function process_function;
};
void Enter_Data(void);
void Control_Variables(void);
struct Menu_Record main_menu[] =
{
{1, "Enter Data", Enter_Data},
{2, "Control Variables {before the get out of control}",
Control_Variables},
{3, "Exit", NULL}
};
const unsigned int NUM_MAIN_OPTIONS =
sizeof (main_menu) / sizeof(main_menu[0]);
int main(void)
{
unsigned int i;
printf("Main Menu:\n");
for (i = 0; i < NUM_MAIN_OPTIONS; ++i)
{
printf("\t(%d) %s\n",
main_menu
.option_number,
main_menu.text);
}
/* enter the selection ... */
/* now process the selection */
for (i = 0; i < NUM_MAIN_OPTIONS; ++i)
{
if (selection == main_menu.option_number)
{
if (main_menu.process_function)
main_menu.process_function();
break;
}
}
return EXIT_SUCCESS;
}
This menu handling method allows you to have many menus
but only require one driver to process the tables. The
number of options can shrink or expand without having
to change the execution code (driver). This method can
be expanded to handle sub-menus too.
It is a nice feeling to spend less than 10 minutes to
update a menu by adding in a new row, rather than having
to locate a switch (or if-else ladder), modify it and
retest (which could take hours or days).