题目要求
将一个句子里面的所有单词顺序反转输出。
AC代码
#include <bits/stdc++.h>
#include <string>
#include <stack>
using namespace std;
int main() {
string input;
while (getline(cin, input)) {
stack<string> s;
string temp;
int index;
while (!input.empty()) { //将input中的所有单词剔出,存入stack中
index = input.find(' ');
if (index != -1) {
temp = input.substr(0, index);
input.erase(0, index + 1);
} else {
temp = input;
input.clear();
}
s.push(temp);
}
while (!s.empty()) { //s出栈,反向输出,注意空格和回车
if (s.size() == 1) {
printf("%s\n", s.top().c_str());
s.pop();
} else {
printf("%s ", s.top().c_str());
s.pop();
}
}
}
return 0;
}