2008-11-27 68 views
37

我目前使用std::ofstream如下:寫作stringstream的內容到ofstream的

std::ofstream outFile; 
outFile.open(output_file); 

然後我嘗試將std::stringstream對象傳遞給outFile如下:

GetHolesResults(..., std::ofstream &outFile){ 
    float x = 1234; 
    std::stringstream ss; 
    ss << x << std::endl; 
    outFile << ss; 
} 

現在我outFile只含有垃圾:「0012E708」全部重複。

GetHolesResults我可以寫

outFile << "Foo" << std:endl; 

,它會輸出正確outFile

任何有關我在做什麼錯誤的建議?

+1

我建議你改一下標題的東西在的行:「書面方式stringstream的內容到ofstream的」(或ostream的什麼事項) – 2008-11-27 22:09:22

+1

埃裏克,你應該紀念約翰的回答所接受,這樣我可以刪除我的(這顯然比他的方法更糟糕) – 2013-07-19 16:30:07

+1

好的,完成了。但是在那些日子裏,我使用了你的解決方案=) – Eric 2013-07-19 16:32:46

回答

67

你可以做到這一點,它不需要創建字符串。它使輸出流讀出右側流的內容(可用於任何流)。

outFile << ss.rdbuf(); 
3

將字符串流rdbuf傳遞給流時不會轉換換行符。輸入文本可以包含\n,因此查找替換不起作用。舊代碼寫入fstream並將其切換到stringstream會丟失endl翻譯。

8

如果您使用std::ostringstream並想知道爲什麼沒有用ss.rdbuf()寫入,那麼使用.str()函數。

outFile << oStream.str();