2009-08-10 34 views
14

我有一個現有的std :: string和一個int。我想將int附加到字符串中,但是以可讀的形式(十六進制表示法)而不是二進制亂碼。如何將數據追加到十六進制格式的std :: string?

通常情況下,我只是用printf,但我不能用的std :: string(可以嗎?)

任何建議,如何做到這一點做到這一點?

Example: 
Given: 
    std::string - "Your Id Number is: " 
    int - 0xdeadc0de 
Output: 
    std::string - "Your Id Number is: 0xdeadc0de" 

回答

30

使用stringstream。您可以使用它作爲任何其他輸出流,所以您可以同樣插入std::hex。然後提取它的stringstream::str()函數。

std::stringstream ss; 
ss << "your id is " << std::hex << 0x0daffa0; 
const std::string s = ss.str(); 
+5

的std :: showbase應另外使用到std ::十六進制以「0x」前綴整型的代表權OP的要求完全匹配 – 2009-08-10 15:00:42

5

建立在xtofl的答案上​​,您正在尋找的標題是<iomanip>。這裏有std::hex,std::decstd::oct直播,所有這些都可以直接導入到流中,以便隨後發送到流中的任何內容都被轉換爲該基礎。

0

我相信'字符串'只能轉發聲明std :: stringstream。所以,你還需要包括:

#include <sstream> 
相關問題