2011-03-02 106 views
14

我試圖用istringstream一個簡單的字符串分割成一系列整數使用istringstream整數:將字符串分割成C++

#include <string> 
#include <iostream> 
#include <sstream> 
#include <vector> 

using namespace std; 

int main(){ 

    string s = "1 2 3"; 
    istringstream iss(s); 

    while (iss) 
    { 
     int n; 
     iss >> n; 
     cout << "* " << n << endl; 
    } 
} 

,我也得到:

* 1 
* 2 
* 3 
* 3 

爲什麼最後一個元素總是出現兩次?如何解決它?

回答

30

它出現了兩次,因爲你的循環是錯誤的,正如http://www.parashift.com/c++-faq-lite/input-output.html#faq-15.5while (iss)與本場景中的while (iss.eof())不相似)中所解釋的那樣。

具體而言,在第三次循環迭代中,iss >> n成功並獲取您的3,並使流處於良好狀態。由於這個良好的狀態,循環第四次運行,直到下一個(第四個)iss >> n失敗,循環條件被破壞。但在第四次迭代結束之前,您仍然會第四次輸出n

嘗試:

#include <string> 
#include <iostream> 
#include <sstream> 
#include <vector> 

using namespace std; 

int main() 
{ 
    string s = "1 2 3"; 
    istringstream iss(s); 
    int n; 

    while (iss >> n) { 
     cout << "* " << n << endl; 
    } 
} 
+0

我們該如何在for()循環中做到這一點? – 2014-01-12 09:31:07

+0

@SumitKandoi:你是什麼意思?你爲什麼? – 2014-01-12 12:43:39

+0

實際上,我在while()循環中試過。我想我們可以在for()循環中做到這一點 – 2014-01-12 14:32:29

0

希望這有助於:
ISS:1 2 3
迭代1
ISS:1 2 3(最初)
n = 1的
ISS:2 3
// * 1打印
迭代2:
ISS:2 3(最初)
n = 2的
ISS:3
// * 2印刷
迭代3
ISS:3
n = 3個的
ISS: ''
迭代4
ISS: ''
N不改變//下垂設置EOF ISS的如從流
ISS沒有進一步的輸入:「」

而作爲正確地通過上述訊息中提到,而(ISS)不是從而不同(iss.eof())。
在內部,函數(istream :: operator >>)首先構造一個sentry對象(將noskipws設置爲false [這意味着空格是分隔符,列表將是1,2,3])來訪問輸入序列。然後(如果good [這裏沒有到達]),它調用num_get::get [獲取下一個整數]來執行提取和解析操作,相應地調整流的內部狀態標誌。最後,它在返回之前銷燬哨兵對象。

請參閱:http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/