美文网首页
字符函数库cctype

字符函数库cctype

作者: 别念_ | 来源:发表于2020-04-16 10:35 被阅读0次
c++从c继承了一个与字符相关的、非常方便的函数库,它可以简化诸如确定字符时候为大写字母,数字,标点符号等。这些函数的原型在头文件<<cctype>> / <<cctype.h>>中。

例如如果ch是一个字母则isalpha(ch)函数返回一个非零值,否则返回0。同样,如果ch是标点符号(如逗号或者句号),函数ispunct(ch)**将返回true(这些函数的返回类型为int,而不是bool,但通常bool转换可以将它们视为bool类型)

使用这个函数比使用&& 和 || 运算符更加方便:

if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){......}
与使用isalpha()相比:
if(isalpha(ch)){......}

isalpha()不仅更容易使用,而且更通用。and/or 格式假设A-Z的字符编码是连续的,其他的字符编码不在这个范围内,这种假设对ASCII码来说也是成立的,但通常并非总是这样。


    char ch;
    int whitespace =0 ,digits = 0 ,chars = 0 ,punct = 0 ,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 << "latters" << endl;
    cout << whitespace << "whitwhitespace" << endl;
    cout << digits << "digits" << endl;
    cout << punct << "punct" << endl;
    cout << others << "others" << endl;

image.png

相关文章

网友评论

      本文标题:字符函数库cctype

      本文链接:https://www.haomeiwen.com/subject/heilvhtx.html