c++ primer 学习之路 (29)6.3 字符函数库cctype

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

结果如下:

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值