输入一段英文,将每个单词的首字母转换为大写。要求编写函数实现转换,在main函数中输入和输出转换后的字符串 用c++写一下
时间: 2024-01-22 20:19:01 浏览: 31
以下是代码实现:
```C++
#include <iostream>
#include <string>
using namespace std;
void capitalize(string& str) {
bool nextCap = true;
for (int i = 0; i < str.length(); ++i) {
if (nextCap && isalpha(str[i])) {
str[i] = toupper(str[i]);
nextCap = false;
}
else if (isspace(str[i])) {
nextCap = true;
}
}
}
int main() {
string inputStr;
getline(cin, inputStr); // 读入整行字符串
capitalize(inputStr);
cout << inputStr << endl;
return 0;
}
```
函数 `capitalize` 实现了将输入字符串中每个单词的首字母转换为大写的操作。具体来说,我们对于字符串中的每个字符,如果该字符是字母并且需要被大写,就将其转换成大写形式,并将 `nextCap` 标记设为 `false`,表示下一个字母不需要大写了。如果该字符是空格,就将 `nextCap` 标记设为 `true`,表示下一个字母需要大写。
在 `main` 函数中,我们首先读入一行字符串,然后调用 `capitalize` 函数进行转换,并输出转换后的字符串。注意,我们使用了 `getline` 函数来读入整行字符串。