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

C++中Vector无法输出最后一个元素,首次运行正常后续失效问题求助

Fixing Your C++ Word Splitting Issue

Hey there, let's break down what's going wrong with your code and fix it step by step.

The Core Problems in Your Current Code

  1. Missing the last word: Your loop only pushes the current word into the vector when it hits a space. But sentences almost never end with a space, so the final word never gets added to myString—it just sits in the word variable after the loop finishes.
  2. Incorrect word reset: When you hit a space, you set word = " " (a string with a space). This means your next word will start with an extra space, which is not what you want. You should reset it to an empty string instead.

Fixed Version of Your Code

Here's the corrected code with explanations of the changes:

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

using namespace std;

int main() {
    string sentence, word;
    vector<string> myString;

    cout << "Enter a sentence: " << endl;
    getline(cin, sentence);

    for (auto x : sentence) {
        if (x == ' ') {
            // Avoid adding empty strings for multiple consecutive spaces
            if (!word.empty()) {
                myString.push_back(word);
                cout << word << endl;
                word = ""; // Reset to empty string instead of a space
            }
        } else {
            word += x; // Shorthand for word = word + x
        }
    }

    // Add the final word after the loop ends (since there's no trailing space)
    if (!word.empty()) {
        myString.push_back(word);
        cout << word << endl;
    }

    // Print all elements in the vector
    cout << "\nAll words in vector:" << endl;
    for (auto elem : myString) {
        cout << elem << endl;
    }

    return 0;
}

Key Changes Made:

  • Added a post-loop check to push the remaining word into the vector (this fixes the missing last word issue).
  • Changed word = " " to word = "" to properly reset the word buffer without extra spaces.
  • Added !word.empty() checks to avoid adding empty strings when there are multiple consecutive spaces.

A More Efficient Alternative (Using stringstream)

For splitting strings into words in C++, using stringstream is a cleaner and more robust approach—it handles all whitespace (including multiple spaces, tabs) automatically:

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

using namespace std;

int main() {
    string sentence, word;
    vector<string> myString;

    cout << "Enter a sentence: " << endl;
    getline(cin, sentence);

    stringstream ss(sentence);
    // Extract words one by one, automatically skipping whitespace
    while (ss >> word) {
        myString.push_back(word);
        cout << word << endl;
    }

    cout << "\nAll words in vector:" << endl;
    for (auto elem : myString) {
        cout << elem << endl;
    }

    return 0;
}

This approach eliminates the need to manually handle each character, reducing the chance of bugs like the one you encountered.

内容的提问来源于stack exchange,提问作者Mr.Longbottom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 22:32:32