运用c++编写一个程序,输入一个字符串,然后计算并输出该字符串中大写字母和小写字母的个数
时间: 2024-06-15 08:07:49 浏览: 151
当使用C++编写一个程序来计算字符串中大写字母和小写字母的个数时,可以按照以下步骤进行:
1. 引入必要的头文件:
```cpp
#include <iostream>
#include <string>
```
2. 定义主函数:
```cpp
int main() {
// 代码将在这里编写
return 0;
}
```
3. 获取用户输入的字符串:
```cpp
std::string input;
std::cout << "请输入一个字符串:";
std::getline(std::cin, input);
```
4. 声明并初始化大写字母和小写字母的计数变量:
```cpp
int uppercaseCount = 0;
int lowercaseCount = 0;
```
5. 遍历字符串中的每个字符,并判断其是否为大写字母或小写字母:
```cpp
for (char c : input) {
if (std::isupper(c)) {
uppercaseCount++;
} else if (std::islower(c)) {
lowercaseCount++;
}
}
```
6. 输出结果:
```cpp
std::cout << "大写字母个数:" << uppercaseCount << std::endl;
std::cout << "小写字母个数:" << lowercaseCount << std::endl;
```
完整代码如下所示:
```cpp
#include <iostream>
#include <string>
int main() {
std::string input;
std::cout << "请输入一个字符串:";
std::getline(std::cin, input);
int uppercaseCount = 0;
int lowercaseCount = 0;
for (char c : input) {
if (std::isupper(c)) {
uppercaseCount++;
} else if (std::islower(c)) {
lowercaseCount++;
}
}
std::cout << "大写字母个数:" << uppercaseCount << std::endl;
std::cout << "小写字母个数:" << lowercaseCount << std::endl;
return 0;
}
```
阅读全文
相关推荐

















