#include<vector> #include <iostream> #include<string> using namespace std; vector<string> v; int main() { string s; getline(cin, s); string tmp; for (int i = 0; i < s.length(); i++) { char c = s[i]; if (c != ' ') tmp += c; else { v.push_back(tmp); tmp = ""; } } v.push_back(tmp); for (auto it = v.rbegin(); it != v.rend(); ++it) { cout << *it << " "; } return 0; }
用vector来存每一个单词,如果碰到空格就将单词插入到vector中,最后将还没有插入的单词插入,然后反向遍历即可。