c++常用的字符处理函数isalnum、isalpha、isupper、iscntrl、isdigit、isgraph、ispunct、isspace、isxdigit、tolower、toupper

一些常用字符处理函数
对于c++中的字符以及字符串相关的程序来说,c++中提供的一些字符处理函数是非常有用的,它们可以判断一个字符的类别并进行字母的大小写转换。这些函数在头文件< ctype.h >中定义。

字符处理函数

#include<iostream>
#include<ctype.h>
#include<stdio.h>
using namespace std;

//字符处理函数

int main()
{
    
    
	char ch = ' ';
	cout << "请输入一些字符,并以‘.’结尾:" << endl;
	do {
    
    
		ch = getchar ();
		cout << "字符:";
		putchar(ch);
		cout << endl;
		if (isalnum(ch))
		{
    
    
			cout << "您输入的是字母或数字!" <<endl;
		}
		if (isalpha(ch))
		{
    
    
			if (isupper(ch))
			{
    
    
				cout << "您输入的是大写字母!" << endl;
				cout << "转换成小写字母是:" << endl;
				putchar(tolower(ch));
				cout << endl;
			}
			else
			{
    
    
				cout << "您输入的是小写字母!" <<endl;
				cout << "转换成大写字母是:" << endl;
				putchar(toupper(ch));
				cout << endl;
			}
		}
		if (iscntrl(ch))
		{
    
    
			cout << "您输入的是控制字符!" << endl;
		}
		if (isdigit(ch))
		{
    
    
			cout << "您输入的是数字!" << endl;
		}
		if (isgraph(ch))
		{
    
    
			cout << "您输入的是可打印字符!" << endl;
		}
		if (ispunct(ch))
		{
    
    
			cout << "您输入的是标点符号!" << endl;
		}
		if (isspace(ch))
		{
    
    
			cout << "您输入的是空白字符!" << endl;
		}
		if (isxdigit(ch))
		{
    
    
			cout << "您输入的是十六进制数!" << endl;
		}
	}
	while ( ch != '.');
	return 0 ;
}

运行结果:
在这里插入图片描述

示例的程序主体是一个循环,在检查到输入为英文句号的时候会结束程序。getchar()和putchar()是两个定义在< stdio.h>的函数,getchar()会从输入端获取一个字符,而putchar()会把一个字符打印到输出端。在这里我们打印了好几个字符,在按下回车键,按下回车键之后每次循环中的getchar()都会读取一个输入过的字符,直到遇到“.”。如果每输入一个字符就按回车键,回车键也会被getchar()读取。

猜你喜欢

转载自blog.csdn.net/m0_62870588/article/details/123737607