思路:利用循环输入流每次读入一个单词,利用cin输入流在读入一个空格时会自动断开的特性,然后将每一个单词加到需要返回的字符串的前面
#include <iostream>
using namespace std;

int main() {
    //利用输入空格则断开的特性
    string s;
    string ans;
    while(cin>>s){
        s+= " "+ans;
        ans=s;
    }
    cout<<ans;
}
思路:循环到空格则利用substr输出子串,注意子串开始位置以及包含字符数。
#include <iostream>
#include <string>
using namespace std;

int main(){
    string str,newstr("");
    getline(cin,str);
    int j = str.length();
    for(int i = str.length()-1; i >= 0; i--){
        if(str[i] == ' '){
            newstr += str.substr(i+1,j-1-i);
            newstr += ' ';
            j = i;
        }
        if(i == 0)
            newstr += str.substr(0,j);
    }
    cout << newstr;
    return 0;
}