将src字节数组从第offset的位置的后面count个转换成一个字符串

awjx 2005-09-23 01:57:11

我设计了如下函数,将src字节数组从第offset的位置的后面count个转换成一个字符串,但执行在CString内部断言失败?怎么回事?
CString Convert::BytesToString(BYTE *src, int offset, int count)
{
CString str ;
for(int i = 0; i<count; i++)
{
str.SetAt(i, str[ offset + i ]);
}
return str;
}

这个函数有问题吗?
为什么我试着执行 str.SetAt(i,'8');都不行?不会SetAt有错吧?
...全文
173 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
NJHS 2005-09-23
  • 打赏
  • 举报
回复
char a[10] = {'1','2','3','4','5','6','7','8','9','\0'};
CString ls = a;
NJHS 2005-09-23
  • 打赏
  • 举报
回复
因为你的CString 对象没有初始化,所以直接使用setat会出错
i_noname 2005-09-23
  • 打赏
  • 举报
回复
你的写法有明显错误,看MSDN的解释:
SetAt will not enlarge the string if the index exceeds the bounds of the existing string.
----------------------------------
CString str ;
for(int i = 0; i<count; i++)
{
str += src[offset + i];
}
return str;
awjx 2005-09-23
  • 打赏
  • 举报
回复
程序没判断,但输入的内部绝对没超出src的范围的。因为str.SetAt(i,'8')都出错!

另:字符数组转为一个字符串,还有其它一步到位的方法吗?
i_noname 2005-09-23
  • 打赏
  • 举报
回复
用memcpy可以实现你要的功能:

char *newstring = new char[count+1];
newstring[count] = '\0';
memcpy(newstring,src+offset,count);
NJHS 2005-09-23
  • 打赏
  • 举报
回复
需要判断offset + count是否超出src的范围了
awjx 2005-09-23
  • 打赏
  • 举报
回复
我写错了,是下面这样的,出错!
CString Convert::BytesToString(BYTE *src, int offset, int count)
{
CString str ;
for(int i = 0; i<count; i++)
{
str.SetAt(i, src[ offset + i ]);
}
return str;
}
NJHS 2005-09-23
  • 打赏
  • 举报
回复
BYTE *src没有使用

怎么会对呢?

18,356

社区成员

发帖
与我相关
我的任务
社区描述
VC/MFC 网络编程
c++c语言开发语言 技术论坛(原bbs)
社区管理员
  • 网络编程
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧