一个函数指针的例子,请看一下问题出在哪?

炼气士 2011-08-28 05:27:11

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


int main(int argc, char* argv[])
{
int ch,t=0;
int num_type[7]={0,0,0,0,0,0,0},total_num=0;
int i = 0;

int (*ctype_h[])(int)={isspace,iscntrl,isdigit,islower,isupper,ispunct,isprint};
while ((ch=getchar())!=EOF&&ch!='\n')
{
i=0;
while (i<7)
{
num_type[i]+=ctype_h[i](ch); // ???
//num_type[i]+=ctype_h[i](ch)?1:0;
i++;
}
total_num++;
}
i=0;
while (i<7)
{
printf("numtype[%d]=%d\n",i,num_type[i]);
i++;
}
printf("total=%d",total_num);
return 0;
}

基本意图是,输入一串字符串,统计空格,控制符,数字等等的个数,然后打印.
运行后,发现统计值每次都是以8来计数的,比如判断到是个空格,则相应的计数加8,而非加1.导致统计后的值要除以8,请问问题出在哪?
...全文
121 12 打赏 收藏 转发到动态 举报
写回复
用AI写文章
12 条回复
切换为时间正序
请发表友善的回复…
发表回复
Roy_Smiling 2011-08-28
  • 打赏
  • 举报
回复
c++ primer ing
modicum_lf 2011-08-28
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 lusemaomaochong 的回复:]

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


int main(int argc, char* argv[])
{
int ch,t=0;
int num_type[7]={0,0,0,0,0,0,0},total_num=0;
int i ……
[/Quote]

++
正解!

AnYidan 2011-08-28
  • 打赏
  • 举报
回复
[Quote=引用 8 楼 pathuang68 的回复:]
单步调式一下就清楚了
[/Quote]
++
炼气士 2011-08-28
  • 打赏
  • 举报
回复
单步试了一下,发现 t = isspace(ch);
返回值确实是8,怎么和百度上对ctype.h的解释不一致,
百度说返回值是0和1
pathuang68 2011-08-28
  • 打赏
  • 举报
回复
单步调式一下就清楚了
炼气士 2011-08-28
  • 打赏
  • 举报
回复
主要是想问一下为什么函数指针的引用返回值不是0或者1,因为isspace,iscntrl,isdigit,islower,isupper,ispunct,isprint这些函数的返回值只有0和1,是不是
我的函数指针哪里用错了,导致返回值不一样?
lichanglianga 2011-08-28
  • 打赏
  • 举报
回复
+1搞错了
仙度瑞城 2011-08-28
  • 打赏
  • 举报
回复
把你注释掉的那句num_type[i]+=ctype_h[i](ch)?1:0;去掉注释
再把前面那句num_type[i]+=ctype_h[i](ch);注释掉
iamnobody 2011-08-28
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 mingliang1212 的回复:]
while (i<7)
{
num_type[i]+=ctype_h[i](ch); // ???
//num_type[i]+=ctype_h[i](ch)?1:0;
i++;
}
total_num++;
问题出在这句,这句是如果出现一个这你列举的类型,就把num_type[i] 的所有数 都+1,这样你要统计什么0?去掉这一句试试
[/Quote]

应该是+1 加7次。搞错了。。。

iamnobody 2011-08-28
  • 打赏
  • 举报
回复
while (i<7)
{
num_type[i]+=ctype_h[i](ch); // ???
//num_type[i]+=ctype_h[i](ch)?1:0;
i++;
}
total_num++;
问题出在这句,这句是如果出现一个这你列举的类型,就把num_type[i] 的所有数 都+1,这样你要统计什么0?去掉这一句试试
lusemaomaochong 2011-08-28
  • 打赏
  • 举报
回复
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>


int main(int argc, char* argv[])
{
int ch,t=0;
int num_type[7]={0,0,0,0,0,0,0},total_num=0;
int i = 0;

int (*ctype_h[])(int)={isspace,iscntrl,isdigit,islower,isupper,ispunct,isprint};
while ((ch=getchar())!=EOF&&ch!='\n')
{
i=0;
while (i<7)
{
//num_type[i]+=ctype_h[i](ch); // ???
num_type[i]+=ctype_h[i](ch)?1:0;
i++;
}
total_num++;
}
i=0;
while (i<7)
{
printf("numtype[%d]=%d\n",i,num_type[i]);
i++;
}
printf("total=%d",total_num);
return 0;
}


游戏设计师 2011-08-28
  • 打赏
  • 举报
回复
((ch=getchar())!=EOF&&ch!='\n')
这个这么写对吗?
对于计数,你看看是不是返回值不对~
或者吧你的那8个函数也贴出来看看~
顺便说一下,你的函数指针参数是int的,判断的是char的不要浪费了~改成char吧~

69,336

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧