Reputation: 1199
I'm having problem to split the string with space as a delim. I have tried 2 of the proposed solution as in here: Split a string in C++? (using copy + istringstream and split method)
However, no matter what I did, the vector only get the first word (not the rest). When I use the split method, it's working with anything else (dot, comma, semi colon...) but not space.
Here is my current code, can you tell me what I get wrong? Or how I should try to approach the fix?
int main()
{
std::vector<std::string> textVector;
std::string textString;
std::cout << "Input command : ";
std::cin >> textString;
std::istringstream iss(textString);
std::copy(std::istream_iterator<std::string>(iss), std::istream_iterator<std::string>(), std::back_inserter(textVector));
for (int i = 0 ; i < textVector.size(); i++) {
std::cout << textVector[i];
}
return 0;
}
The runnable code: http://cpp.sh/8nzq
Upvotes: 0
Views: 1309
Reputation: 62787
Reason is simple, std::cin >> textString
only reads until first whitespace. So textString
only contains the first word.
To read entire line, you should instead use: std::getline(std::cin, textString);
Upvotes: 1