Menu
CoddyTech

数字字符数量

Coddy 用 C++ 编写简单的字符计数器 课程的第 5 课,共 5 课。

在 C++ 中,你可以使用以下方法检查一个字符是否是数字:

bool b = std::isdigit(c)

如果 c 是数字,b 的值为 true,否则为 false。

或者,使用命名空间时,可以简写为:

bool b = isdigit(c)
challenge icon

挑战

简单

在现有程序中添加统计字符串中数字个数的功能,并在最后按下面的格式输出(另起一行):

Number of digits: XX

不要删除之前的输出,在当前输出之后输出它。

亲手试试

#include <iostream>
#include <string>
using namespace std;

int main() {
    string text;

    cout << "Enter text:" << endl;
    getline(cin, text);

    int total = 0;
    int totalLetters = 0;
    for (char c : text) {
        if (c == ' ') {
            continue;
        }

        total++;

        if (isalpha(c)) {
            totalLetters++;
        }
    }

    cout << "Total characters: " << total << endl;
    cout << "Total letters: " << totalLetters << endl;
    return 0;
}

用 C++ 编写简单的字符计数器中的所有课

自己练习: C++ 在线编译器

统计任意文本的字数: 字数统计