看板 C_and_CPP 關於我們 聯絡資訊
int main() { double x = 0.222222; string someData = "apple"; int k = 0; while (k <= 10) { ofstream outFile("output.txt"); ostringstream fn; fn << "file" << k << ".txt"; ofstream out(fn.str().c_str(), ios_base::binary); out.write(&someData[0], someData.size()); k++; } } 這是一個連續創造出file0.txt, file1.txt, ... ,file10.txt 的C++程式碼 txt裡面都是"apple"字串. 我的問題是: 如果txt的內容要改成儲存浮點數, x, 請問要怎麼修改這個程式碼? 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 118.189.197.194 ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1434897411.A.33B.html ※ 編輯: ej001 (118.189.197.194), 06/21/2015 22:37:26 ※ 編輯: ej001 (118.189.197.194), 06/21/2015 22:46:36
MOONRAKER: 有什麼理由非要用write()寫嗎 06/21 22:50
ej001: 不知道, 因為這範本的作者不是我 06/21 22:52
ej001: 如果有更好的想法, 麻煩跟我講 謝謝 06/21 22:53
LPH66: 哪裡找來的範本? 06/21 23:04
ej001: stackoverflow 06/21 23:15
cory8249: 直接 out << x << endl; 不就好了 ? 06/21 23:21
anyoiuo: 裡面"已經"是浮點數,只是這樣是二進制應該是IEEE754格式 06/22 09:29
anyoiuo: ofstream來輸出字串有問題,請使用stringstream 06/22 09:30
anyoiuo: 10進輸出參考cory8249大大說的 06/22 09:31
anyoiuo: 樓上無視,看錯了那是沒使用到的code 06/22 09:32
MOONRAKER: 好一個爛範例。 06/22 10:07
ej001: 這範例還不錯用 改用out輸出即可, thanks to cory. 06/22 18:56