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;
}
字符函數名稱及返回值如下: