字符串返回错误的长度
char concat to string returns wrong length
简单的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";
您没有像您认为的那样将char
与std::string
串联。这是因为"test"
实际上是一个字面的const char*
,因此当您向其添加x
时,您只是在执行指针算术。您可以替换
test = x + "test";
test = std::to_string(x) + "test";
然后您的输出将为
length: 5
test: 1test
相关文章:
- (C++)分析树以计算返回错误值的简单算术表达式
- 为什么与常规GCC不同,即使有"学究性错误",MinGW-GCC也能容忍丢失的返回类型
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 我不断收到 [错误] ID 返回 1 退出状态错误,但看不到问题所在
- C++中函数的向量返回类型引发错误
- 有人知道为什么在开关中使用stoi函数会返回恒定的错误吗
- glad 导致 glfwSwapBuffers 返回错误消息
- 将错误返回给调用方而不是立即在 C++ 中抛出错误是否是一种好的做法
- QNX Momentics: GoogleMock - 返回有价值,在函数中返回 void 错误
- 我的模板类方法返回错误类型?
- C++ 中的编译错误:未定义对"主"的引用 collect2:错误:ld 返回 1 个退出状态
- 替换WCHAR_T错误返回存储地址
- 错误:void 值未被忽略,因为它应该被忽略,错误:返回语句具有值
- 带有值的递归阶乘错误返回语句,在函数中返回 'void' [-fallowive]
- 存储在静态常量整数 (C++) 中的对数函数的错误返回值
- 更丰富的错误返回消息用于提升::精神::qi 解析
- C++初级逻辑错误-返回0
- 由于进程很多,pthread_create的错误返回代码是 35 错误,我用过pthread_exit应该杀死线程不是吗?
- c++错误处理返回值错误返回
- systememerror:没有异常集的错误返回