#include <stdio.h> #include <stdlib.h> char* menu[] = { "a - add new record", "d = delete record", "q - quit", NULL, }; // int func(int a[]) // a is a pointer to the first element of an array // int func(int* a) // is the same as the above one // so I think the below one is equal to char** choices); // int getchoice(char* greet, char* choices[]); int getchoice(char* greet, char** choices); int main() { int choice = 0; do { choice = getchoice("please select an action", menu); printf("you have chosen: %c/n", choice); } while(choice != ‘q‘); exit(0); } int getchoice(char* greet, char** choices) // int getchoice(char* greet, char* choices[]) { int chosen = 0; int selected; char** option; do { printf("choice: %s/n", greet); option = choices; while (*option) { printf("%s/n", *option); option++; } // when prog running, when user types ‘a‘ and Enter key, prog see ‘a‘ and // LF(‘/n‘)(10), not the character CR‘/r‘(13), unix and linux use a single // LF as the end of a line not like in windows it use both the two characters // but still strange happens, this program runs very well in both linux and // windows OS. do // if I typed ‘a‘ and Enter in shell bash, there will be two characters in { // buffer, character ‘a‘(97) and character ‘/n‘(10), selected = getchar(); } while (selected == ‘/n‘); // discard the ‘/n‘ option = choices; while (*option) { if (selected == *option[0]) { chosen = 1; break; } option++; } if (!chosen) { printf("incorrect choice, select again/n"); } } while (!chosen); return selected; }
时间: 2024-11-06 02:42:17