思路:

对字符串的每一个字符进行判断,判断是否为字母,如果为字母则保留到临时字符串tmp中,如果下一个字符也是字母,则与加入字符串tmp末尾;如果不为字母,则将临时字符串tmp加入栈中,并清空字符串tmp。按照此规则一直循环到字符串末尾。 到字符串末尾时,如果末尾的字符为字母,则需要将tmp中的临时字符串加入栈中。如果末尾的字符不是字母,此时的临时字符串为空,不需要加入栈中。

代码:

#include<bits/stdc++.h>
using namespace std;

int main(){
    string str;
    stack<string> result;

    getline(cin,str);   // 有空格

    string tmp;
    int i = 0;
    for (i = 0; i < str.size(); i++)
    {
        if((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')){
            tmp += str[i];
        }else{
            result.push(tmp);
            tmp.clear();
        }
    }
    if((str[i-1]>='a' && str[i-1]<='z') || (str[i-1]>='A' && str[i-1]<='Z')){
        result.push(tmp);
    }

    while(!result.empty()){
        cout << result.top() << " ";
        result.pop();
    }
    cout << endl;

    return 0;
}