在C中,将字符从一个数组连接到另一个数组
Concatenate chars from one array to another in C
我有一个包含26000行或记录的文本文件。每个记录包含128字节的十六进制数据。
我需要一次提取4条记录,将其放入另一个数据结构中,并在套接字上发送
以下是的代码片段
std::string array[26000];
char* char_ptr = NULL;
char data[512];
for(int index = 0; index < 26000; index += 4)
{
// copy data
char_ptr = &(array[index]);
memcpy(&data, char_ptr, sizeof(data));
// send data on socket
}
这只提供字符串数组中的第4个128字节记录。我如何从字符串数组中获取4条记录或512字节的数据,并将其复制到char-data[]变量中
感谢您的帮助
首先,std::string
与字节数组不是一回事。
其次,构建这四个记录块的最简单方法可能是内部循环。
for(int index = 0; index < 26000; index += 4)
{
// copy data
for (int j=0; j<4; j++) {
assert(array[index+j].size() == 128);
memcpy((data)+(128*j), array[index+j]+data(), 128);
}
// send data on socket
}
最后,正如其他答案所指出的,使用C样式数组容易出错;在以后使用std::string
或其他STL类型可能会更好,比如在套接字上实际发送数据时。
我建议您避免混合使用C和C++代码。以下是如何做到这一点:
#include <numeric>
#include <string>
std::string array[26000];
const int add = 4;
for (int i = 0; i < 26000; i += add)
{
std::string data;
data = std::accumulate(array + i, array + i + add, data);
// send data on socket
}
我甚至替换了std::vector上的26000个元素的第一个数组,并替换了size()方法调用中的常量26000。使用C样式数组很容易出错。
您有26000个std::string
对象,每个对象都有自己的内部数据,不能保证从一个对象到下一个对象都有连续的内部缓冲区。您的解决方案是修改循环对象,以便在填充data
数组时分别使用每个对象。
循环计数变量正在向上计数4,但您只获取了一条记录。我认为更好的方法是让字符串对象为您负责内存分配,然后从生成的字符串中获取字符并将其发送出去。
for(int i = 0; i < 26000; i += 4)
{
string four_recs = array[i] + array[i+1] + array[i+2] + array[i+3];
// Extract characters
char *byte_data = new char [four_recs.length()];
for (int j = 0; j < four_recs.length()]; j++)
byte_data[j] = four_recs[j];
// Send it out
}