字符串返回错误的长度

char concat to string returns wrong length

本文关键字:错误 返回 字符串      更新时间:2023-10-16

简单的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 | |
+---+---+---+---+---+
  +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";

然后您的输出将为

length: 5
test: 1test