描述编写程序读入一行英文只包含字母和空格单词间以单个空格分隔将所有单词的顺序倒排并输出依然以单个空格分隔。输入描述输入为一个字符串字符串长度至多为100。输出描述输出为按要求排序后的字符串。希望能用c++编写代码
你可以使用C++的字符串处理函数和循环来实现此功能。以下是一个可能的解决方案:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
int main() {
std::string input;
std::getline(std::cin, input); // 读取输入字符串
std::string word;
std::vector<std::string> words;
// 使用循环遍历输入字符串,将单词存入vector中
for (char c : input) {
if (c == ' ') {
if (!word.empty()) {
words.push_back(word);
word.clear();
}
} else {
word += c;
}
}
// 最后一个单词需要额外处理
if (!word.empty()) {
words.push_back(word);
}
// 倒序输出单词
std::reverse(words.begin(), words.end());
// 输出结果
for (const std::string& w : words) {
std::cout << w << " ";
}
std::cout << std::endl;
return 0;
}
这个程序首先读取输入字符串,然后使用一个循环遍历字符串中的每个字符。如果字符是空格,则将之前存储的单词加入到vector中,并清空word变量。否则,将字符添加到word中。最后一个单词需要在循环结束后额外处理。
接下来,使用std::reverse函数将vector中的单词进行倒序排序。
最后,使用循环输出倒序后的单词,并在单词之间添加一个空格。注意,最后一个单词后面不要输出多余的空格。
希望这可以帮助到你
原文地址: http://www.cveoy.top/t/topic/iSgJ 著作权归作者所有。请勿转载和采集!