使用 << 或 >> 连接无符号字符数组

Using << or >> to concatenate a unsigned char array

本文关键字:gt lt 字符 数组 无符号 使用 连接      更新时间:2023-10-16

如果我有这 2 个数组:

unsigned char bytes1[n];
unsigned char bytes2[m];

(nm是任意整数),我这样做:

cout << bytes1 << bytes2;

我设法显示这 2 个数组的内容。是否可以使用此概念来连接这两个数组?像这样:

usigned char bytes1[2];
unsigned char bytes2[3];
unsigned char * bytes3 = new unsigned char[5];
bytes3 << bytes1 << bytes2;

最后,bytes2应该依次具有bytes1bytes2的内容。

您可能希望在此上下文中使用stringstream

此处引用: http://www.cplusplus.com/reference/sstream/stringstream/?kw=stringstream

在标题中:

#include <sstream>

在体内:

unsigned char bytes1[2];
unsigned char bytes2[3];
unsigned char * bytes3 = new unsigned char[5];
std::stringstream ss;
ss << bytes1 << bytes2;
ss >> bytes3
//This should be also good
std::string bytes3 = ss.str();

您的原始代码不起作用byte3因为它不是stream(特别是ostream),因此它没有<<运算符