CString对象copy的小错误

来源:百度知道 编辑:UC知道 时间:2024/05/25 22:08:07
CString a,b;
a=_T("abcdefg");
for(int i=0;i<5,i++)
b.SetAt(i,a[i]);//此处导致 “Debug Assertion Failed”

刚执行就出错了,提示中有:Expression: (iChar >=0) && (iChar <= GetLength()),谁教教我。。
另外 CString之间的copy有没有类似strncopy,wcsncpy功能的不用转换的函数
谢谢大家给的答案,虽然没有回答错误原因,但给了我不少启发,功能实现用CString::mid了。错误原因我心里有答案了,只是想看看和大家的解释是否一致,期待

Remarks
SetAt will not cause the array to grow. Use SetAtGrow if you want the array to grow automatically.

You must ensure that your index value represents a valid position in the array. If it is out of bounds, then the Debug version of the library asserts.

很明显,你对b的访问越界了

b=a //这样是直接赋值

b.Left(5) //这样子是取左边 就是你要的功能

方法多的是,看看CString的成员函数就知道了
b = a; //操作符=赋值
b = a.Left( 5); //取a左边5个字符赋值
b = a.Right(5); //取a右边5个字符赋值
b.Format(_T("%5.5s"), a); //使用Format格式化赋值
b = _T("") + a; //运算符+

错误原因:a和b是CString的对象,并不是指针,所以你通过a[i]访问a的第i个字符是错误的,具体可以调试时看断言信息

我不知道你想做什么,要实现字符串a Copy 到字符串b中吗?
哪为什么不用b=a呢?