- 使用getline获取一行字符串
- 使用空格“ ”代替字符串中非字母数字;
- 使用stringstream对处理过后的数据进行逐个单词读取,会自动跳过空格;
- 使用vector储存每个单词,然后用reverse函数倒排;
- 输出单词和空格,注意最后一个单词没有空格,最后输出换行符。
#include <bits/stdc++.h> using namespace std; int main() { string line; while(getline(cin, line)) { for(auto &c : line) { if(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z') { continue; } else { c = ' '; } } stringstream ss(line); string word; vector<string> vec; while(ss >> word) { vec.push_back(word); } reverse(vec.begin(), vec.end()); for(int i = 0; i < vec.size(); i++) { cout << vec[i]; if(i != vec.size() - 1) { cout << " "; } } cout << endl; } }