Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1467855
  • 博文数量: 218
  • 博客积分: 6394
  • 博客等级: 准将
  • 技术积分: 2563
  • 用 户 组: 普通用户
  • 注册时间: 2008-02-08 15:33
个人简介

持之以恒

文章分类

全部博文(218)

文章存档

2013年(8)

2012年(2)

2011年(21)

2010年(55)

2009年(116)

2008年(16)

分类: C/C++

2010-08-21 13:42:44

例子说明:
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;
阅读(4924) | 评论(2) | 转发(0) |
给主人留下些什么吧!~~

GilBert19872010-08-21 17:39:41

是啊,我没给id.c_str()直接赋值啊

chinaunix网友2010-08-21 16:25:06

怪怪,你没看到id.c_str()返回的是const char*么???