6.3 字符函数库cctype
C++从C语言继承了一个与字符相关的、非常方便的函数软件包,它可以简化诸如确定字符是否为大写字母、数字、标点符号等工作,这些函数的原型是在头文件cctype(老式的风格中为ctype.h)中定义的。例如,如果ch是一个字母,则isalpha(ch)函数返回一个非零值,否则返回0。同样,如果ch是标点符号(如逗号或句号),函数ispunct(ch)将返回true。(这些函数的返回类型为int,而不是bool,但通常bool转换让您能够将它们视为bool类型。)
程序清单6.8演示一些ctype库函数。具体地说,它使用isalpha( )来检查字符是否为字母字符,使用isdigits( )来测试字符是否为数字字符,如3,使用isspace( )来测试字符是否为空白,如换行符、空格和制表符,使用ispunct( )来测试字符是否为标点符号。该程序还复习了if else if结构,并在一个while循环中使用了cin.get(char)。
#include<iostream>
#include<cctype>
using namespace std;
int main()
{
cout << "Enter text for analysis,and type @ to terminate input\n ";
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 << "puncuations, "
<< others << "others.\n";
system("pause");
return 0;
}
结果如下: