我有一个类型的缓冲区char*
和一个string
. 我想将string
长度 +放在缓冲区内string
。
我编写了以下代码来完成此操作,但它不起作用,因为std::cout<<strlen(buffer)
无论我作为函数的参数传递什么字符串,都会打印“1”。
int VariableLengthRecord :: pack (const std::string strToPack)
{
int strToPackSize = strToPack.length();
if (sizeof(strToPackSize) + strToPackSize > maxBytes - nextByte)
return RES_RECORD_TOO_LONG; // The string is too long
int start = nextByte;
// Copy the string length into the buffer
copyIntToBuffer((buffer+start),strToPackSize);
// Copy the string into the buffer
strcpy((buffer+start+sizeof(strToPackSize)),strToPack.c_str());
// Move the buffer pointer
nextByte += sizeof(strToPackSize) + strToPackSize;
// Update buffer size
bufferSize = nextByte;
std::cout << "Size of buffer = " << strlen(buffer) << std::endl;
return RES_OK;
}
void copyIntToBuffer (char* buffer, int integer)
{
buffer[0] = integer & 0xff;
buffer[1] = (integer >> 8) & 0xff;
buffer[2] = (integer >> 16) & 0xff;
buffer[3] = (integer >> 24) & 0xff;
}