c++学习笔记——字符函数库cctype

 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值