输入一段英文,将每个单词的首字母转换为大写。要求编写函数实现转换,在main函数中输入和输出转换后的字符串。
时间: 2024-02-12 13:07:22 浏览: 27
以下是实现该功能的 C++ 代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
string capitalize(string sentence) {
// 将第一个单词的首字母转换为大写
sentence[0] = toupper(sentence[0]);
// 遍历每个字符,如果前一个字符是空格,则将当前字符转换为大写
for (int i = 1; i < sentence.length(); i++) {
if (sentence[i - 1] == ' ') {
sentence[i] = toupper(sentence[i]);
}
}
return sentence;
}
int main() {
string input;
cout << "请输入一段英文:";
getline(cin, input); // 使用 getline 获取一行输入
string output = capitalize(input);
cout << "转换后的字符串为:" << output << endl;
return 0;
}
```
运行程序后,输入一段英文,如 "hello world! this is a test.",输出将会是 "Hello World! This Is A Test."。
注意,该函数只会将每个单词的首字母转换为大写,其余字母都会保持不变。如果需要将整个字符串都转换为大写或小写,可以使用 `toupper()` 或 `tolower()` 函数。