Jump to content

Menu: Difference between revisions

31 bytes added ,  14 years ago
→‎{{header|C}}: Fixed behaviour for non-integer input.
(→‎{{header|C++}}: corrected; simplified)
(→‎{{header|C}}: Fixed behaviour for non-integer input.)
Line 64:
#include <string.h>
 
const char *menu_select(const char **items, const char *prompt);
 
int
const char *menu_select(const char **items, const char *prompt)
int 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(menuitems, "Which is from the three pigs?"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;
return NULL;
 
do {
for 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>
 
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.