您的位置:首页 > 其它

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

2013-11-18 16:29 302 查看
// 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变量,利用编译器对其自动初始化,也行这并不是一个好主意!!
不要在同一个地方犯第二次错误,故记录下~~~







                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐