Converting int[] to String in C++

前端 未结 6 1246
星月不相逢
星月不相逢 2020-12-16 06:26

I have a string defined as std::string header = \"00110033\"; now I need the string to hold the byte values of the digits as if its constructed like this

6条回答
  •  太阳男子
    2020-12-16 07:14

    Do this:

      char data_bytes[] = { '0', '0', '1', '1', '0', '0', '3', '3', '\0'};
      std::string header(data_bytes, 8);
    

    Or maybe, you want to do this:

      std::stringstream s;
      s << data_bytes;
      std::string header = s.str();
    

    Demo at ideone : http://ideone.com/RzrYY


    EDIT:

    Last \0 in data_bytes is necessary. Also see this interesting output here: http://ideone.com/aYtlL

    PS: I didn't know this before, thanks to Ashot I came to know this difference by experimenting!

提交回复
热议问题