字符函数库cctype
cctype
1.c++从从语言继承了一个与字符相关的函数软件包,可以确定字符是否为大写字母,数字,标点符号。这些函数的必须在头文件cctype中定义。
如:如果ch是一个字母,则isalpha(ch)函数返回一个非0值,否则返回0。同样,如果ch是标点符号,函数ispunct(ch)将返回true。这些函数的返回类型为int,而不是bool,但通常bool转换让我们能够将它们视为bool类型。
2.使用&&和||运算符来测试字符ch是否为字母:
if((ch>='a' && ch<='z')||(ch>='A'&&ch<='Z'))
与使用isalpha()相比:
if(isalpha(ch))
isalpha是不是跟方便,通用。
例子:使用isalpha()函数来检查字符是否为字母字符,使用isdigits()来测试字符是否为数字字符,使用isspace()函数来测试字符是否为空白如:换行符,空格,制表符。使用ispuntct来测试字符是否为标点符号。
#include <iostream>
#include<cctype>
using namespace std;
int main()
{
cout<<"Enter text for analysis,and type @"
"to terminate input"<<endl;
char ch;
int whitespace=0;
int digits=0;
int chars=0;
int punct=0;
int others=0;
cin.get(ch);
while(ch !='@')
{
if(isalpha(ch))
chars++;
else if(isspace(ch))
whitespace++;
else if(isdigit(ch))
digits++;
else if(ispunct(ch))
punct++;
else
others++;
cin.get(ch);
}
cout<<chars<<"letters,"
<<whitespace<<"whitespace,"
<<digits<<"digits,"
<<punct<<"punctuations,"
<<others<<"others"<<endl;
return 0;
}
运行:注意,空白字符计数中包括换行符。
3.像这样的函数还有很多,如下表所示: