C++从C语言继承了一个与字符相关的、非常方便的函数软件包,它可以简化诸如确定字符是否为大写字母、数字、标点符号等工作,这些函数的原型是在头文件cctype(老式的风格中为ctype.h)中定义的。
例如,如果ch是一个字母,则isalpha(ch)函数返回一个非零值,否则返回0。同样如果ch是标点符号(如逗号或句号),函数ispunct(ch)则返回true。(这些函数的返回类型为int,而不是bool,但通常bool转换让您能够将它们视为bool类型。)
示例如下:
#include <iostream>
#include <string>
#include <cctype>
using namespace std;
int main()
{
char ch;
int chars = 0;
int digits = 0;
int puncts = 0;
int others = 0;
cin.get(ch);
while ('\n' != ch)
{
if (isalpha(ch))
chars++;
else if (isdigit(ch))
digits++;
else if (ispunct(ch))
puncts++;
else
others++;
cin.get(ch);
}
cout << chars << "chars" << endl;
cout << digits << "digits" << endl;
cout << puncts << "puncts" << endl;
cout << others << "others" << endl;
return 0;
}
字符函数名称及返回值如下: