轉到重複問題以瞭解如何將字符串拆分爲單詞,但您的方法實際上是正確的。實際的問題在於你如何讀取輸入之前試圖分裂它:
string tempInput;
cin >> tempInput; // !!!
當您使用cin >> tempInput
,你只從輸入,而不是整個文本獲得的第一個字。有工作你的出路是兩種可能的方式,其中最簡單的是忘掉了stringstream
,並直接迭代輸入:
std::string tempInput;
std::vector<std::string> tokens;
while (std::cin >> tempInput) {
tokens.push_back(tempInput);
}
// alternatively, including algorithm and iterator headers:
std::vector<std::string> tokens;
std::copy(std::istream_iterator<std::string>(std::cin),
std::istream_iterator<std::string>(),
std::back_inserter(tokens));
這種方法會給你輸入的所有的標記在一個單一的矢量。如果您需要與各行的工作separatedly那麼你應該使用getline
從<string>
頭,而不是cin >> tempInput
:
std::string tempInput;
while (getline(std::cin, tempInput)) { // read line
// tokenize the line, possibly with your own code or
// any answer in the 'duplicate' question
}
不是一個真正的欺騙。這是「我在哪裏犯錯誤」vs「什麼是......的最佳方式」? – 2010-04-28 08:20:30
雖然問題是完全一樣的:如何分割一個字符串,我相信@pmr提到的問題處理通用問題,而在這個問題中,問題不在於實際分裂 – 2010-04-28 08:21:28
@David @SF是的,你是對的。不幸的是,大多數答案不會以這種方式處理問題。 – pmr 2010-04-28 08:29:53