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

C++句子单词逆序输出问题求助及代码修复

单词逆序输出程序故障修复

问题描述

需要编写程序读取一行少于50个单词的文本,逆序输出句子中的单词(例如输入Today is Tuesday,输出Tuesday is Today)。原代码逻辑是将单词存入数组后从后往前打印,但运行异常:数组最后一个元素存储了整个句子,且输出包含大量空内容。

原代码:

#include <bits/stdc++.h>
using namespace std;

int main(){
    string str;
    cout<<"Put in your sentence: ";
    getline(cin,str);
    string strWords[10];
    int counter = 0;
    for (int i = 0; i<str.length(); i++){
    if (str[i] == ' ')
        counter++;
    else
        strWords[counter] += str[i];
    }

    int j=9;
    do{
        cout<<j<<": "<<strWords[j]<<" ";
        j--;
    }
    while(j>=0);

    return 0;
}

示例输入输出:

输入:
Put in your sentence: WE are the people.
输出:
9: WE are the people. 8: 7: 6: 5: 4: 3: people. 2: the 1: are 0: WE

问题分析

  1. 数组越界引发未定义行为:原代码使用固定大小的strWords[10]数组,若单词数量接近或超过10,会越界写入栈内存,覆盖其他变量数据(这就是索引9出现整个句子的原因)。
  2. 打印逻辑错误:从数组最大索引9开始打印,而有效单词仅存储在0到counter的索引中,后续索引均为空字符串。
  3. 未处理连续空格:输入中若有多个连续空格,会导致counter多次递增,产生空的单词元素。

修复方案

方案1:使用动态容器(推荐)

用vector<string>动态存储单词,避免数组大小限制,同时优化单词分割逻辑:

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

using namespace std;

int main() {
    string str;
    cout << "Put in your sentence: ";
    getline(cin, str);
    
    vector<string> words;
    string currentWord;
    
    for (char c : str) {
        if (c == ' ') {
            if (!currentWord.empty()) {
                words.push_back(currentWord);
                currentWord.clear();
            }
        } else {
            currentWord += c;
        }
    }
    // 处理最后一个无空格结尾的单词
    if (!currentWord.empty()) {
        words.push_back(currentWord);
    }
    
    // 逆序打印有效单词
    for (auto it = words.rbegin(); it != words.rend(); ++it) {
        cout << *it << " ";
    }
    cout << endl;
    
    return 0;
}

方案2:使用固定数组(适配原思路)

调整数组大小为50(符合题目“少于50个单词”的限制),优化分割和打印逻辑:

#include <iostream>
#include <string>

using namespace std;

int main() {
    string str;
    cout << "Put in your sentence: ";
    getline(cin, str);
    
    string strWords[50];
    int counter = 0;
    string currentWord;
    
    for (int i = 0; i < str.length(); i++) {
        if (str[i] == ' ') {
            if (!currentWord.empty()) {
                strWords[counter] = currentWord;
                counter++;
                currentWord.clear();
            }
        } else {
            currentWord += str[i];
        }
    }
    // 添加最后一个单词
    if (!currentWord.empty()) {
        strWords[counter] = currentWord;
        counter++;
    }
    
    // 从最后一个有效单词开始逆序打印
    for (int j = counter - 1; j >= 0; j--) {
        cout << strWords[j] << " ";
    }
    cout << endl;
    
    return 0;
}

修复说明

  • 动态容器vector自动扩容,彻底避免数组越界问题。
  • 单词分割时仅在当前单词非空时存入容器,跳过连续空格。
  • 循环结束后手动添加最后一个单词(无空格结尾),避免遗漏。
  • 打印时仅遍历有效单词索引,不再输出空内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:55:27