有多个单词,以空格分割。返回每个单词的首字母并大写。

唯一的问题就在于如果读取多个以空格为分隔符的单词。如果直接写一个cin肯定是不行的,因为cin以空格作为分隔符,会导致只能获取第一个单词。

解法1:利用getline,getline可以获取一行内容,它默认以换行作为分隔符,所以可以读取所有单词。接下来只需要遍历字符串,分别获取首字母即可。

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

int main()
{
    string s, ret;
    getline(cin,s);

    ret += s[0] <= 'z' && s[0] >= 'a' ? (char)(s[0] - 32) : s[0]; // 第一个大写字母
    size_t index = s.find(' '); // 利用find函数,找到空格;如果找不到会返回npos
    while(index != s.npos)
    {
        if(s[index + 1] <= 'z' && s[index + 1] >= 'a')
            ret += (char)(s[index + 1]  - 32);
        else ret += s[index + 1];
        index = s.find(' ',index + 1); // 从该位置向后继续找空格
    }
    cout << ret << endl;

    return 0;
}

解法2:我们可以利用多组输入,利用while循环每次只读取一个单词,直接取单词的首字母即可。

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

int main()
{
    string s;
    while (cin >> s)//以空格作为分隔符,每次读取一个单词
    {
        if (s[0] <= 'z' && s[0] >= 'a') cout << (char)(s[0] - 32);
        else cout << s[0];
    }
    return 0;
}