2013-06-27 36 views
0

我想通過ostringstream將int轉換爲字符串,但每次將數據放入流中時,都會保留在流中。我試過使用.flush()<<endl,但是這個流不會清空。 This question暗示我真的沒有流(我不知道,仍然在努力),我正在做的事情是喧鬧和不必要的。爲什麼ostringstream不能清空?

int main() 
{ 
    long int max = 0; 
    ostringstream strs; 
    for(int i=10;i<100; i++){ 
    for(int j = i; j < 100; j++){ 
     long int product = i*j; 
     strs.flush(); 
     strs <<product; 

     string str = strs.str(); 
     cout<<str; 
     int size = str.length(); 
    } 
    } 
    cout<<max; 
    return 0; 
} 

目前我得到的

100/100 
110/100110 
120/100110120 
130/100110120130 
etc... 

,而不是

100/100 
110/110 
120/120 
130/130 
etc... 
+0

爲什麼*會*爲空?文件的內容不會因爲讀取而消失,是嗎?從流中讀取只是獲取流中的數據,而不會刪除流中的內容。 –

+0

你甚至讀過ostringstream的文檔,尤其是它的成員函數,尤其是flush嗎? – PlasmaHH

+0

@PlasmaHH yup,它說'flush:Flush output stream buffer'。我認爲這會解決問題。我很困惑,因爲我使用它的方式,它不是 – Daniel

回答

3

std::ostringstream是一個作家接口到〜應變G。使用<<附加到字符串,並且flush是多餘的,因爲該字符串沒有緩衝區。

要改變到的數據流寫入(如空單)的字符串,利用其str()成員函數的設定版本:

strs << product; 
string str = strs.str(); 
strs.str(""); // reset string written into 
0

清晰的輸出ostringstream.buffer這樣的:

strs.str(""); 
+3

這只是重置標誌,它不會更改字符串緩衝區的內容。 – PlasmaHH

+0

更正後感謝 – suspectus

0

要重置std::ostringstream,你只是分配一個新的緩衝區:

std::ostringstream oss; 
// ... 
oss.str(std::string()); 

然而,多數認爲是沒有必要的,因爲你可以定義/初始化範圍最窄可能你的stringstream的自動獲取,時間。在你的情況下,你可能想要在outer for循環中定義它。

+0

-1:這不行,'str()'返回底層字符串的*副本*。 – Angew

+0

你說得對。改編。 – arne

0

將ostringstream放入範圍,以便每次輸入時都會重新創建它。你的情況將是:

int main() 
{ 
    long int max = 0; 
    { 
    ostringstream strs; 
    for(int i=10;i<100; i++){ 
    for(int j = i; j < 100; j++){ 
     long int product = i*j; 
     strs.flush(); 
     strs <<product; 

     string str = strs.str(); 
     cout<<str; 
     int size = str.length(); 
    } 
    } 
} 

    cout<<max; 
    return 0; 
} 
1

到目前爲止處理這個最簡單的方法是創建一個新的stringstream對象,你希望它是空的每一次。在大多數情況下(包括你的),只需簡單地讓現有對象超出範圍,並在重新輸入正確的範圍時創建一個新對象,就可以輕鬆處理。

就個人而言,我會通過移動所有的代碼從int轉換爲std::string到具有本地的stringstream對象的函數做的工作,所以一個「乾淨」的stringstream創建每次調用函數時,並摧毀當你離開它時。

std::string to_string(long int in) { 
    std::stringstream buffer; // New/empty every time this function is called 
    buffer << in; 
    return buffer.str(); 
}        // here buffer goes out of scope and is destroyed. 

int main() 
{ 
    long int max = 0; 
    for(int i=10;i<100; i++){ 
    for(int j = i; j < 100; j++) { 
     long int product = static_cast<long>(i)*j; 
     std::string str = to_string(product); 

     // presumably: 
     // if (product > max) max = product; 

     std::cout << str; 

     // you never seem to use this: 
     //int size = str.length(); 
    } 
    } 
    cout<<max; 
    return 0; 
} 

有兩點要注意:如果你的編譯器是比較新的,它可能已經在其標準庫的std::to_string,所以你可以使用,而不是寫你自己的。

另請注意,在ij之間乘以long即可。鑑於您現在使用的值,這不是嚴格必要的,但long也不是product。假設你可能使用product可能大於int的值,那麼演員就變得有必要了。沒有它,你在兩個int s上進行乘法運算,這自然會產生一個int結果。然後你正在接受那個結果(如果它太大而不能適應int就會溢出)並將其轉換爲long。通過在乘法之前將其中一個操作數轉換爲long,您也可以強制在long s上執行乘法運算,從而防止溢出(至少假設long足夠大以容納結果)。

相關問題