c++从c语言继承了一个与字符相关的、非常方便的函数软件包,它可以简化像确定字符是否是大写字母,数字或者标点之类的工作,这些函数的原型在头文件cctype中定义的。
// cctypes.cpp -- using the ctype.h library
#include <iostream>
#include <cctype> // prototypes for character functions
int main()
{
using namespace std;
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); // get first character
while (ch != '@') // test for sentinel
{
if(isalpha(ch))
// isalpha(ch)函数检查是否是字母,是字母函数isalpha()返回true,否则返回false。
//等效与if (ch >= 'a' && ch <= 'z || ch >= 'A' && ch <= 'Z);
//因为AND/OR运算符假设A-Z的字符编码是连续的,其他字母的编码不在这个范围内。这种假设一般对ascii成立。
chars++;
else if(isspace(ch)) // isspace()检查是否是空白,如换行符、空格、制表符。
whitespace++;
else if(isdigit(ch)) //是否是数字
digits++;
else if(ispunct(ch)) //
punct++;
else
others++;
cin.get(ch); // get next character
}
cout << chars << " letters, "
<< whitespace << " whitespace, "
<< digits << " digits, "
<< punct << " punctuations, "
<< others << " others.\n";
// cin.get();
// cin.get();
return 0;
}
Enter text for analysis, and type @ to terminate input.
you are beautifu.@
14 letters, 2 whitespace, 0 digits, 1 punctuations, 0 others.