您的位置:首页 > 编程语言 > C语言/C++

C++(6)C风格字符串

2015-08-07 18:56 579 查看


C风格字符串

序言:

尽管现代C++支持C风格字符串,但是不应该在C++程序中使用这个类型。C风格字符串常常带来许多的错误,是导致大量安全问题的根源!

C风格字符串可以理解为是“以空字符null结尾的数组”.

[cpp] view
plaincopy





//请注意下面两条语句的区别

char strErr[] = {'C','+','+'};

char strOk[] = "C++";

正文:

1、C++通过(const)char*类型的指针来操纵C风格字符串。

[cpp] view
plaincopy





const char *str = "some values";

/*

*如果str所指的字符串不是以null结尾,那么循环调用会失败,

*循环从str指向的位置开始读数,直到内存中某处null结束符为止

*/

while (*str)

{

cout << *str;

++ str;

}

2、C风格字符串的标准库函数:strncat,strncpy

1)在使用C风格字符串的标准库函数时,一定不要忘记字符串一定要以null结尾!

[cpp] view
plaincopy





//不会有好的结果...

char str[] = {'C','+','+'};

cout << strlen(str) << endl;

2)如果必须使用C风格字符串,则使用函数 strncat 和 strncpy 会比 strcat 和 strcpy 更加安全

[cpp] view
plaincopy





char largeStr[16 + 18 + 2];



strncpy(largeStr,cp1,17);

/*

*在调用strncat时,原来用于结束largeStr的null被

*新添加的空格覆盖,然后在空格后面写入新的结束符null

*/

strncat(largeStr," ",2);

strncat(largeStr,cp2,19);

3、尽量使用string代替

一是提高了安全性,二是提高了效率!

[cpp] view
plaincopy





//P116 习题4.22 解释下面两个程序的区别

//(1)

int main()

{

const char *cp = "hello";

int cnt = 0;



while (*cp)

{

++cnt;

cout << *cp;

++ cp;

}

cout << '\n' << cnt << endl;

}



//(2)

int main()

{

const char *cp = "hello";

int cnt = 0;



while (cp)

{

++cnt;

cout << *cp;

++ cp;

}

cout << '\n' << cnt << endl;

}

[cpp] view
plaincopy





//习题4.23 解释写列程序能够实现什么功能

int main()

{

const char ca[] = {'H','e','l','l','o'};

const char *cp = ca;

cout << strlen(cp) << endl;

while (*cp)

{

cout << *cp;

++ cp;

}

cout << endl;

cout << strlen(ca) << endl;

cout << strlen(cp) << endl;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: