写个C和指针习题程序犯太多错误,记下提醒自己

// c_chapt13_1.cpp : Defines the entry point for the console application.
//编写程序,从标准输入读取一些字符,并根据分类计算各类字符所占的百分比
//禁止使用一系列if或者switch语句

#include "stdafx.h"
#include <cstdio>
#include <cctype>

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



int _tmain(int argc, _TCHAR* argv[])
{

	//声明函数指针
	int (*classity_char[])(int)={
		iscntrl,//判断控制字符
		isspace,
		isdigit,
		islower,
		isupper,
		ispunct,
		is_not_print
	};

	//声明各种字母名称数组
	char *name_of_chars[]={
		"control",
		"whitespace",
		"digit",
		"lower case",
		"upper case",
		"punctuation",
		"non printable"
	};

	//声明各种字母数量数组
	//int numbers_of_chars=(sizeof(classity_char)/sizeof(classity_char[0]));
	const int numbers_of_chars=(sizeof(classity_char)/sizeof(classity_char[0]));
	//#define numbers_of_chars ( sizeof( classity_char )/sizeof( classity_char[0] ) )
	static int numbers[ numbers_of_chars ];
	int total=0;
	char ch;
	//输入字母并判断
	while ( (ch=getchar())!=EOF )
	{
		total+=1;
		for(int i=0;i<numbers_of_chars;++i)
		{
			if ( classity_char[i]( ch ) )
				numbers[i]+=1;
		}
	}
	
	//输出结果
	if (0==total)
	{
		printf("There is no print.");
	}
	else
	{
		for (int i=0;i<numbers_of_chars;++i)
		{
			printf("%f%% %s characters\n",numbers[i]*100.0/total,name_of_chars[i]);
		}
	}
	printf("\n\n\nThank you!!!");
	return 0;
}
错误1:
int is_not_print(int ch)
{
	return !isprint(ch);
}
写成 
int is_not_print(int)
{
	return !isprint(int);
}
Error2 error C2660: 'isprint' : function does not take 0 argumentsd:\我的c++\练习\c_chapt13_1\c_chapt13_1\c_chapt13_1.cpp11

错误2:关于定义数组大小
int numbers_of_chars=(sizeof(classity_char)/sizeof(classity_char[0]));
错误:1>d:\我的c++\练习\c_chapt13_1\c_chapt13_1\c_chapt13_1.cpp(45) : error C2057: expected constant expression
1>d:\我的c++\练习\c_chapt13_1\c_chapt13_1\c_chapt13_1.cpp(45) : error C2466: cannot allocate an array of constant size 0
1>d:\我的c++\练习\c_chapt13_1\c_chapt13_1\c_chapt13_1.cpp(45) : error C2133: 'numbers' : unknown size
数组大小定义时应为常量,而代码中给的是变量,顾出现上述错误,可以定义成const。

错误3:宏定义不是语句,不应该加分号。
#define numbers_of_chars ( sizeof( classity_char )/sizeof( classity_char[0] ) )
虽说知道概念,但是使用时还是出现错误,因为本人很少这样使用,习惯性加了分号,导致任何一个使用该宏的地方都有错误。谨记!!!

错误4:未初始化数组,
编译无错后,运行结果莫名其妙。于是F9设置断点观察numbers数组数据,发现不对劲。才发现为初始化数组。
由于数组元素都初始化为0,我将其设置成static变量,利用编译器对其自动初始化,也行这并不是一个好主意!!
不要在同一个地方犯第二次错误,故记录下~~~







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值