0

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

Community
  • 1
  • 1
Tree Nguyen
  • 1,198
  • 1
  • 14
  • 37

1 Answers1

1

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);

hyde
  • 60,639
  • 21
  • 115
  • 176
  • Thanks. I thought the problem is with the split :D – Tree Nguyen Oct 09 '15 at 11:32
  • 2
    It's common problem to "think", to assume, instead of to "verify". I would go as far as to say, when ever things stop making sense, it's time to stop thinking for a while, and just do some testing, usually either with a debugger, or with debug prints, or with a separate dummy test program :-) – hyde Oct 09 '15 at 11:35
  • ... and that's why we _require_ a [complete, minimal testcase](http://stackoverflow.com/help/mcve). Because you should already have done your due diligence with one. – Lightness Races in Orbit Oct 09 '15 at 11:37