指针转移表的使用

编写一个程序,从标准输入字符,并根据下面分类统计字符个数;

控制字符

空白字符

数字

小写字母

大写字母

标点符号

不可打印字符

 

 

 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

 

 

/*判断字符是否可以打印*/

int is_not_printf(int ch)
{
 return !isprint(ch);
}

 

/*用于区别类型的分类函数跳转表,函数大部为系统函数*/

int (*test_func[])(int) =
{
 iscntrl,
 isspace,
 isdigit,
 islower,
 isupper,
 ispunct,
 is_not_printf
};

 

/*定义数组大小,增加通用性*/

#define  N_CATE (sizeof(test_func)/sizeof(test_func[0]))

 

/*定义打印的字符说明*/

char *label[] =
{
 "control",
    "space",
 "digit",
 "lower",
 "upper",
 "punct",
 "non-print"
};

 

int main()
{
 int coun[N_CATE]={0,0,0,0,0,0,0};/*偷懒的数组初始化,应该用循环初始以便增加通用性,这里不改了*/
 int totol = 0;
 int ch;
 int categ;
 while((ch=getchar()) != EOF)
 {
  totol += 1;
  for(categ = 0;categ < N_CATE;categ +=1)
  {
   if(test_func[categ](ch))
   {
    coun[categ] += 1;
    break;/*匹配成功则跳出,提高效率*/
   }
  }
 }

 for(categ = 0;categ < N_CATE; categ++)
 {
  printf("%s = %d/n",label[categ],coun[categ]);
 }
    getchar();
 return 0;
}

 

 

 

转移表其实就是函数指针数组,这样使用可以避免使用if,case之类的匹配函数,看着好看点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值