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
- Missing the last word: Your loop only pushes the current
wordinto the vector when it hits a space. But sentences almost never end with a space, so the final word never gets added tomyString—it just sits in thewordvariable after the loop finishes. - 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
wordinto the vector (this fixes the missing last word issue). - Changed
word = " "toword = ""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
相关产品推荐
相关产品推荐

