关于字符串操作strncat

来源:互联网 发布:sql 拆分字符串 编辑:程序博客网 时间:2024/06/06 10:06

在用strncat进行字符串操作时,老是出现编译通过但运行出错--->发送错误。

 

错误代码:

#include <iostream.h>
#include <string.h>
void main(void)
{
char str1[] = "Tsinghua ";
char str2[] = "//";
//cout <<strncat(str1,str2,30)<<endl;
cout<< strncat(str1,str2,3)<< endl;
}

 

 

正确代码:

#include <iostream.h>
#include <string.h>
void main(void)
{
char str1[10] = "Tsinghua ";
char str2[10] = "//";
//cout <<strncat(str1,str2,30)<<endl;

 

cout<< strncat(str1,str2,3)<< endl;
}

 

 

糊涂了,后来上面两个有都可以运行了。。。。 我猜测是编译的bug,留下原来的正确痕迹,但是删除原来编译的链接还是不行,不得已我修改了一下变量,因为我怀疑变量被分配的地址已被固定所以可能,两者又都正确了,我只要修改一下变量,使得编译器重新分配一下变量地址这样就能辨别出谁是金子谁是沙子了,果然下面是我随意改的

错误的代码:

#include <iostream.h>
#include <string.h>
void main(void)
{
    char str1[] = {"12Tsinghua "};
    char str2[] = {"123//"};
//cout <<strncat(str1,str2,30)<<endl;
cout<< strncat(str1,str2,3)<< endl;
}

 

正确的代码:

#include <iostream.h>
#include <string.h>
void main(void)
{
    char str1[20] = {"12Tsinghua "};
    char str2[20] = {"123//"};
//cout <<strncat(str1,str2,30)<<endl;
cout<< strncat(str1,str2,3)<< endl;
}

 

 

关于CString的方法Left、Right、Mid

CString str;

str.Left(nIndex);和str.Mid(nIndex);

关于边界的问题,即从下标的字符开始还是从小标的前一个开始。

一个例子就清楚明了:

str = "zhangleo";

str.Left(2); TRACE(str);     ------------>   str=zh    nIdex就是从左走nIndex个字符(注意没有nIndex=0,这种说明没有字符显示)

str.Right(2); TRACE(str);     ------------>   str=eo   这个同Left只是方向不同,所以==>Left/Right中的nIndex表示的就是要显示的字数个数。它们分别相当于str.Mid(0,nIndex)和str.Mid(str.GetLenght()-1,nIndex). 《注意》->str.GetLength()是含字符个数,如“leo”含字符个数为3.

str.Mid(1); TRACE(str);     ------------>   str=hangeo

str.Mid(1,4); TRACE(str);     ------------>   str=hang   4表示的总共显示的字符总数,1是对应下标

即Left()方法从nIndex的前一个字符开始向左走!不包括nInex下标对应的位置

即Mid()方法从nIndex对应的字符开始向右走!不包括nInex下标对应的位置

 

原创粉丝点击