char concat to string returns 长度错误

char concat to string returns wrong length

将 char 字节添加到字符串的简单 C++ 程序。结果长度在输出中是错误的。

#include <iostream>
#include <string>

int main(){

   char x = 0x01;

   std::string test;
   test = x+"test";

   std::cout << "length: " << test.length() << std::endl;
   std::cout << "test: " << test << std::endl;
   return 0;
}

输出:

length: 3
test: est

我在字符串前面加上一个类型字节,因为我要通过套接字发送此数据,而另一端有一个工厂需要知道要创建的对象的类型。

1 + "test" = "est"  // 1 offset from test

所以你得到了正确的答案。

+---+---+---+---+---+
| t | e | s | t | [=11=]|
+---+---+---+---+---+
  +0  +1  +2  +3  +4

你想要的可能是:

std::string test;
test += x;
test += "test";

您没有像您认为的那样将 charstd::string 连接起来。这是因为 "test" 实际上是一个字面量 const char*,所以当你向它添加 x 时,你只是在做指针运算。你可以替换

test = x + "test";

test = std::to_string(x) + "test";

那么你的output will be

length: 5
test: 1test