1. 程式人生 > >C++ premier Plus書之--C++的cctype介紹

C++ premier Plus書之--C++的cctype介紹

看一個對cctype中主要方法的介紹的例子:

#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;
}

程式執行結果為:

以下是cctype裡主要的函式及作用:
isalnum() 判斷傳入的引數是否是字母或者數字, 是返回true, 否則false
isalpha() 判斷是否是字母
iscntrl() 判斷是否是控制字元
isdigit() 判斷是否是0~9的數字
isgraph() 是否是出空格之外的列印字元
islower() 是否是小寫字母
isprint() 是否是列印字元(包含空格)
ispunct() 是否是標點符號
isspace() 是否是空白字元, 如:空格, 換行符, 回車, 製表符等
isupper() 是否是大寫字母
isxdigit() 是否是十六進位制數字
tolower() 轉化為小寫字元
toupper() 轉化為大寫字元