Menu: Difference between revisions

Content added Content deleted
(→‎{{header|C++}}: corrected; simplified)
(→‎{{header|C}}: Fixed behaviour for non-integer input.)
Line 64: Line 64:
#include <string.h>
#include <string.h>


char *menu_select(char **items, char *prompt);


int
const char *menu_select(const char **items, const char *prompt)
main(void)
{
{
char *items[] = {"fee fie", "huff and puff", "mirror mirror", "tick tock", NULL};
int i, nchoices;
char *prompt = "Which is from the three pigs?";
int choice;


printf("You chose %s.\n", menu_select(items, prompt));
if (items==NULL) return NULL;
while(1) {
for(i=0; items[i] != NULL; i++) {
printf("%d) %s\n", i+1, items[i]);
}
nchoices = i;
if ( prompt != NULL )
printf("%s ", prompt);
else
printf("Choice? ");
scanf("%d", &choice);
if ( (choice > 0) && (choice <= nchoices) ) break;
printf("Choose from 1 to %d\n\n", nchoices);
}
return items[choice-1];
}</lang>


return EXIT_SUCCESS;
<lang c>const char *menu[] = {
}
"fee fie", "huff and puff", "mirror mirror", "tick tock", NULL
};


char *
int main()
menu_select(char **items, char *prompt)
{
{
char buf[BUFSIZ];
printf("You chose: %s\n", menu_select(menu, "Which is from the three pigs?"));
int i;
return EXIT_SUCCESS;
int choice;
int choice_max;

if (items == NULL)
return NULL;

do {
for (i = 0; items[i] != NULL; i++) {
printf("%d) %s\n", i + 1, items[i]);
}
choice_max = i;
if (prompt != NULL)
printf("%s ", prompt);
else
printf("Choice? ");
if (fgets(buf, sizeof(buf), stdin) != NULL) {
choice = atoi(buf);
}
} while (1 > choice || choice > choice_max);

return items[choice - 1];
}</lang>
}</lang>