使用流,你的情況,一個字符串流:
#include <sstream>
...
std::stringstream ss;
ss << n << '/' << d;
後來,當你的工作完成後,你可以將其存儲作爲一個普通的字符串:
const std::string s = ss.str();
重要(邊)注:從不做
const char *s = ss.str().c_str();
stringstream::str()
產生臨時std::string
,並根據該標準,臨時對象住直到表達式的結尾。然後,std::string::c_str()
給你一個指向一個以null結尾的字符串的指針,但根據聖律,一旦std::string
(你從中接收它)改變,那麼C風格字符串將變爲無效。
It might work this time, and next time, and even on QA, but explodes right in the face of your most valuable customer.
的std::string
必須生存,直到戰鬥結束:
const std::string s = ss.str(); // must exist as long as sz is being used
const char *sz = s.c_str();
處開始閱讀心理檢查出來,請稍候。 ..錯誤:無法讀取OP的頭腦。發佈該死的錯誤。 – 2011-06-16 07:21:05
它已經在討論:http://stackoverflow.com/questions/191757/c-concatenate-string-and-int – 2011-06-16 07:22:08
我想獲得地圖<雙,字符串>其中double是分數(n/d)和字符串是(「n/d」),那麼我想將它打印到文件 – torayeff 2011-06-16 07:22:46