直接使用一个栈将字符串分割为字符串数组,依次入栈,最后出栈。方法比较笨,仅供参考。

#include<stack>
#include<iostream>
#include<cstring>
#include<vector>>
using namespace std;

vector<string> split(const string& str, const string& delim) {
    vector<string> res;
    if("" == str) return res;
    char * strs = new char[str.length() + 1] ; 
    strcpy(strs, str.c_str()); 

    char * d = new char[delim.length() + 1];
    strcpy(d, delim.c_str());

    char *p = strtok(strs, d);
    while(p) {
        string s = p;
        res.push_back(s); 
        p = strtok(NULL, d);
    }
    delete strs;
    delete d;
    return res;
}

int main(){
    string str;
    getline(cin,str);
    stack<string> stk;
    vector<string> arr = split(str, " ");
    for(auto s: arr){
        stk.push(s);
    }
    string res;
    while(!stk.empty()){
        string t = stk.top();
        stk.pop();
        if(!stk.empty())
            res.append(t+" ");
        else
            res.append(t);
    }
    cout << res;
}