#include"stdafx.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
// #include <opencv2/opencv.hpp>
#define LEN 81
char showmenu(void);
// 读取至行尾
void eatline(void);
void show(void(*fp)(char *), char *str);
// 字符串转换为大写
void ToUpper(char *);
// 字符串转换为小写
void ToLower(char *);
// 大小写转置
void Transpose(char *);
// 不做更改
void Dummy(char *);
char *s_gets(char*st, int n);
int main(int, char**)
{
char line[LEN];
char copy[LEN];
char choice;
// 声明一个函数指针,被指向的函数接受char*类型的参数,无返回值
void(*pfun)(char *);
puts("enter a string (empty line to quit):");
while (s_gets(line, LEN) != NULL && line[0] != '\0') {
while ((choice = showmenu()) != 'n') {
switch (choice) {
// 选择
case 'u':pfun = ToUpper; break;
case 'l':pfun = ToLower; break;
case 't':pfun = Transpose; break;
case 'o':pfun = Dummy; break;
}
// 复制一个副本,为show()函数使用
strcpy(copy, line);
// 根据用户的选择,使用选定的函数
show(pfun, copy);
}
puts("enter a string (empty line to quit):");
}
puts("bye");
return 0;
}
// 用以消除字符输入回车带入的换行符
char *s_gets(char*st, int n) {
char *ret_val;
char *find;
ret_val = fgets(st, n, stdin);
// 查找换行符
if (ret_val) {
find = strchr(st, '\n');
// 如果地址不是NULL
if (find)
// 此处放置一个空字符
*find = '\0';
else
while (getchar() != '\n')
// 清理输入行
continue;
}
return ret_val;
}
char showmenu(void) {
char ans;
puts("enter menu choice:");
puts("u) uppercase 1)lowercase");
puts("t)transposed case o)orignal case");
puts("n)next string");
ans = getchar();
ans = tolower(ans);
eatline();
while (strchr("ulton", ans) == NULL) {
puts("please enter a u, l, t, o, or n:");
ans = tolower(getchar());
eatline();
}
return ans;
}
void eatline(void) {
while (getchar() != '\n')
continue;
}
void ToUpper(char *str) {
while (*str) {
*str = tolower(*str);
str++;
}
}
void ToLower(char *str) {
while (*str) {
*str = tolower(*str);
str++;
}
}
void Transpose(char *str) {
while (*str) {
if (islower(*str))
*str = toupper(*str);
else if(isupper(*str))
*str = tolower(*str);
str++;
}
}
void Dummy(char *str) {
// 不改变字符串
}
void show(void(*fp)(char *), char *str) {
// 把用户指定的字符串函数作用于str
(*fp)(str);
puts(str);
}
c语言实现函数指针小demo
最新推荐文章于 2023-05-18 20:25:43 发布