1 /*------------------------------ 2 func_ptr.c -- 使用函数指针 3 ------------------------------*/ 4 5 #include 6 #include 7 #include 8 9 #define LEN 81 10 11 char* s_gets(char *st, int n); 12 char showmenu(void); 13 void eatline(void); //读取至行末尾 14 void ToUpper(char*); //把字符串转换为大写 15 void ToLower(char*); //把字符串转换为小写 16 void Transpose(char*); //大小写转换 17 void Dummy(char*); //不更改字符串 18 void show(void (*fp)(char*), char *str); 19 20 21 int main() 22 { 23 char line[LEN], copy[LEN]; 24 char choice; 25 void (*pfn)(char*); //声明函数指针 26 27 puts("Enter a string (empty line to quit):"); 28 29 while (s_gets(line, LEN) != NULL && line[0] != '\0') 30 { 31 while ((choice = showmenu()) != '\n') 32 { 33 switch (choice) 34 { 35 case 'u': pfn = ToUpper; break; 36 case 'l': pfn = ToLower; break; 37 case 't': pfn = Transpose; break; 38 case 'o': pfn = Dummy; break; 39 } 40 41 strcpy(copy, line); //为 show() 函数拷贝一份 42 show(pfn, copy); //根据用户选择,使用选定的函数 43 } 44 45 puts("Enter a string (empty line to quit):"); 46 } 47 48 puts("Bye!"); 49 50 return 0; 51 } 52 53 char showmenu() 54 { 55 char ans; 56 57 puts("Enter menu choice:"); 58 puts("u) uppercase 1) lowercase"); 59 puts("t) transposed case o) original case"); 60 puts("n) next string"); 61 62 ans = tolower(fgetc(stdin)); //获取用户输入,转换为小写 63 eatline(); //清理输入行 64 65 while (strchr("ulton", ans) == NULL) 66 { 67 puts("Please enter a u, l, t, o, or n:"); 68 ans = tolower(fgetc(stdin)); 69 eatline(); 70 } 71 72 return ans; 73 } 74 75 void eatline(void) 76 { 77 while (fgetc(stdin) != '\n') continue; 78 } 79 80 void ToUpper(char *str) 81 { 82 while (*str) 83 { 84 *str = toupper(*str); 85 ++str; 86 } 87 } 88 89 void ToLower(char *str) 90 { 91 while (*str) 92 { 93 *str = tolower(*str); 94 ++str; 95 } 96 } 97 98 void Transpose(char *str) 99 {100 while (*str)101 {102 if (islower(*str))103 *str = toupper(*str);104 else if (isupper(*str))105 *str = tolower(*str);106 107 ++str;108 }109 }110 111 void Dummy(char *str)112 {113 //do nothing114 }115 116 void show(void (*fp)(char*), char *str)117 {118 (*fp)(str); //把用户选定的函数作用于str119 puts(str); //显示结果120 }121 122 char* s_gets(char *st, int n)123 {124 char *ret_val, *find;125 126 if (ret_val = fgets(st, n, stdin))127 {128 if (find = strchr(st, '\n'))129 *find = '\0';130 else131 while (fgetc(stdin) != '\n') continue;132 }133 134 return ret_val;135 }