簡體   English   中英

用空格分割字符串,但只得到第一個單詞

[英]Split string with space but only get first word

我在用空格分隔字符串時遇到問題。 我在這里嘗試了2種建議的解決方案: 在C ++中拆分字符串? (使用copy + istringstream和split方法)

但是,無論我做什么,向量都只會得到第一個單詞(而不是其余單詞)。 當我使用split方法時,它可以與其他任何方式(點,逗號,半冒號...)一起使用,但不能與空格配合使用。

這是我當前的代碼,您能告訴我我錯了嗎? 或者我應該如何嘗試解決問題?

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

可運行的代碼: http : //cpp.sh/8nzq

原因很簡單, std::cin >> textString僅讀取直到第一個空格。 因此, textString僅包含第一個單詞。

要讀取整行,應改為使用: std::getline(std::cin, textString);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM