简体   繁体   English

用空格分割字符串,但只得到第一个单词

[英]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++? 我在这里尝试了2种建议的解决方案: 在C ++中拆分字符串? (using copy + istringstream and split method) (使用copy + istringstream和split方法)

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. 当我使用split方法时,它可以与其他任何方式(点,逗号,半冒号...)一起使用,但不能与空格配合使用。

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 可运行的代码: http : //cpp.sh/8nzq

Reason is simple, std::cin >> textString only reads until first whitespace. 原因很简单, std::cin >> textString仅读取直到第一个空格。 So textString only contains the first word. 因此, textString仅包含第一个单词。

To read entire line, you should instead use: std::getline(std::cin, textString); 要读取整行,应改为使用: std::getline(std::cin, textString);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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