代码之家  ›  专栏  ›  技术社区  ›  foobarfuzzbizz

如何将数据附加到十六进制格式的std::string?

  •  17
  • foobarfuzzbizz  · 技术社区  · 15 年前

    我有一个现有的 std::string 和一个 int . 我想将整数的ASCII(字符串文本)十六进制表示连接到 标准::字符串 .

    例如 :

     std::string msg = "Your Id Number is: ";
     unsigned int num = 0xdeadc0de; //3735929054
    

    所需字符串 :

    std::string output = "Your Id Number is: 0xdeadc0de";
    

    通常,我只使用printf,但我不能用std::string(可以吗?)

    有什么建议吗?

    3 回复  |  直到 7 年前
        1
  •  33
  •   xtofl Adam Rosenfield    15 年前

    使用Stringstream。您可以将它用作任何其他输出流,这样您就可以平等地插入 std::hex 进入它。然后提取它 stringstream::str() 功能。

    std::stringstream ss;
    ss << "your id is " << std::hex << 0x0daffa0;
    const std::string s = ss.str();
    
        2
  •  5
  •   Meredith L. Patterson    15 年前

    根据Xtofl的答案,你要找的标题是 <iomanip> . 这里就是 std::hex , std::dec std::oct 活的,所有这些都可以被引导到流中,这样在它们转换到该基之后,任何东西都可以被发送到流中。

        3
  •  0
  •   DevByStarlight    12 年前

    我相信“string”只向前声明std::stringstream。因此,您还需要包括:

    #include <sstream>