例子说明:
char buffer[100];
memset(buffer,'\0',100);
char * p = buffer;
int type = 3;
memcpy(p,(char *)(&type),sizeof(int));
p += sizeof(int);
std::string id = "TS20090506001";
int length = id.length() + 1;
memcpy(p,id.c_str(),length);
p += length;
std::string sendString = buffer;(出现问题)
int guessLength = sendString.length();
m_socket->send(sendString.c_str(),guessLength);
=============================================
guessLength是多少,答案是1;问题出在了
std::string sendString = buffer;
因为sendString拷贝到buffer中的'\0'就不再进行拷贝了
正确的写法是:
char buffer[100];
memset(buffer,'\0',100);
char * p = buffer;
int type = 3;
memcpy(p,(char *)(&type),sizeof(int));
p += sizeof(int);
std::string id = "TS20090506001";
int length = id.length() + 1;
memcpy(p,id.c_str(),length);
p += length;
int guessLength = p - buffer;
m_socket->send(buffer,guessLength);
解析的时候也很好解析:
int type = 0;
char * p = buffer;
memcpy(&type,p,sizeof(int));
p += sizeof(int);
std::string id;
id = p;//std::string operator =()
int length = id.length() +1;
p += length;
阅读(4980) | 评论(2) | 转发(0) |