描述 输入一个句子(一行),将句子中的每一个单词从后往前输出。 输入 只有一行,为一个字符串,不超过500个字符。单词之间以空格隔开(可能含有多个空格) 题目保证句子前和句子后没有空格 输出 将句子中的每一个单词从后往前输出,单词之间的空格需与原文一致 输入样例 1 hello world 输出样例1 world hello c++代码
时间: 2024-04-17 14:28:43 浏览: 110
#include <iostream>
#include <string>
#include <stack>
using namespace std;
string reverseWords(string sentence) {
stack<string> words;
string word = "";
// Extracting words from the sentence
for (int i = 0; i < sentence.length(); i++) {
if (sentence[i] == ' ') {
if (!word.empty()) {
words.push(word);
word = "";
}
} else {
word += sentence[i];
}
}
// Pushing the last word into the stack
if (!word.empty()) {
words.push(word);
}
string reversedSentence = "";
// Constructing the reversed sentence
while (!words.empty()) {
reversedSentence += words.top();
words.pop();
if (!words.empty()) {
reversedSentence += " ";
}
}
return reversedSentence;
}
int main() {
string sentence;
getline(cin, sentence);
string reversedSentence = reverseWords(sentence);
cout << reversedSentence << endl;
return 0;
}
阅读全文