- 题目要求编写一个程序,输入一个长度不超过40的字符串,统计其中大写字母、小写字母、数字字符的个数,并输出结果。用C++编程
时间: 2024-12-29 11:34:49 浏览: 85
在C++中,你可以编写一个简单的函数来实现这个功能。这里是一个基本的示例程序:
```cpp
#include <iostream>
#include <cctype> // 包含处理字符类别所需的头文件
void countCharacterTypes(const std::string& input) {
int upperCase = 0;
int lowerCase = 0;
int digit = 0;
for (char c : input) {
if (isupper(c)) { // 检查是否为大写字母
upperCase++;
} else if (islower(c)) { // 检查是否为小写字母
lowerCase++;
} else if (isdigit(c)) { // 检查是否为数字
digit++;
}
}
std::cout << "大写字母个数: " << upperCase << "\n";
std::cout << "小写字母个数: " << lowerCase << "\n";
std::cout << "数字字符个数: " << digit << "\n";
}
int main() {
std::string userInput;
std::cout << "请输入一个长度不超过40的字符串: ";
std::getline(std::cin, userInput); // 确保获取整个行的内容,包括空格
if (userInput.length() > 40) {
std::cerr << "错误:输入字符串超过40个字符。\n";
} else {
countCharacterTypes(userInput);
}
return 0;
}
```
在这个程序中,我们首先包含了`<cctype>`头文件,它提供了一些用于检查字符类型的函数。然后,我们定义了一个名为`countCharacterTypes`的函数,接受一个字符串作为参数。遍历每个字符,通过`isupper()`、`islower()`和`isdigit()`函数分别检查并计数大写字母、小写字母和数字字符的数量。
在`main`函数中,我们从用户那里获取输入,并在输入过长时给出错误提示。如果输入符合条件,就调用`countCharacterTypes`函数并打印出结果。
阅读全文
相关推荐















