C++ 编写程序实现英文单词倒序输出

本程序使用 C++ 语言编写,实现将一行英文单词(以空格分隔)进行倒序输出的功能。代码简洁易懂,并附带详细的注释说明。

输入描述

输入为一个字符串(字符串长度至多为 100),包含字母和空格,单词间以单个空格分隔。

输出描述

输出为按要求排序后的字符串,即单词顺序倒置,依然以单个空格分隔。

**代码示例:**cpp#include #include #include #include

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;}

代码说明:

  1. 首先,使用 std::getline 函数读取输入的字符串。2. 使用一个循环遍历输入字符串,将单词存入 std::vector 中。3. 当遇到空格时,判断当前 word 是否为空,如果非空则将其加入到 words 向量中,并清空 word 变量。4. 循环结束后,最后一位可能还有单词,需要额外处理。5. 使用 std::reverse 函数将 words 向量中的单词进行倒序排列。6. 使用一个循环输出倒序后的单词,并在单词之间添加一个空格。

示例运行:

输入:

This is a test string

输出:

string test a is This

总结:

本程序利用 C++ 的字符串处理函数和循环,实现了将英文单词倒序输出的功能,代码简洁易懂,易于理解和修改。

C++ 编写程序实现英文单词倒序输出

原文地址: https://www.cveoy.top/t/topic/qyhg 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录