简体   繁体   中英

Split string with space but only get first word

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM