You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++长单词反转函数输出顺序错误问题求助

问题分析与修正

你的代码存在两个核心问题,导致输出顺序颠倒且单词处理异常:

1. 单词拆分逻辑错误

原代码中,无论当前字符是否为空格,都会执行x = x + str[i],这会导致空格被混入单词中。比如处理"fellow"时,前面的空格会被加入x,使得单词变为" fellow",长度计算和反转结果都会出错。

2. 结果拼接顺序完全颠倒

你将最后一个单词赋值给y作为起始,然后循环把之前存在vector里的单词追加到后面,直接反转了整个句子的单词顺序。


修正后的代码

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

std::string spinWords(const std::string &str)
{
    std::string currentWord = "";
    std::vector<std::string> words;
    
    for (char c : str) {
        if (c == ' ') {
            if (!currentWord.empty()) {
                // 反转长度超过5的单词
                if (currentWord.length() > 5) {
                    std::reverse(currentWord.begin(), currentWord.end());
                }
                words.push_back(currentWord);
                currentWord.clear();
            }
        } else {
            currentWord += c;
        }
    }
    
    // 处理最后一个未被空格截断的单词
    if (!currentWord.empty()) {
        if (currentWord.length() > 5) {
            std::reverse(currentWord.begin(), currentWord.end());
        }
        words.push_back(currentWord);
    }
    
    // 按原顺序拼接所有单词
    std::string result;
    for (size_t i = 0; i < words.size(); ++i) {
        if (i != 0) {
            result += " ";
        }
        result += words[i];
    }
    
    return result;
}

int main(){
    std::cout << "\n" << spinWords("Welcome"); // 输出 emocleW
    std::cout << "\n" << spinWords("Hey fellow warriors"); // 输出 Hey wollef sroirraw
}

关键修改说明

  • 纯净的单词拆分:仅将非空格字符加入当前单词,遇到空格时处理并保存当前单词,避免空格混入。
  • 统一管理所有单词:把最后一个单词也处理后存入vector,确保所有单词的顺序与原输入一致。
  • 正确拼接逻辑:按vector的顺序拼接单词,仅在单词之间添加空格,避免多余空格,同时保证句子顺序正确。
  • 可读性优化:使用更清晰的变量名,用范围for循环遍历字符,符合C++代码规范。

内容的提问来源于stack exchange,提问作者AlanWat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:48:16