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;
}
相关文章推荐
- [C/C++标准库]_[初级]_[std::vector的多线程读写问题]
- [C/C++标准库]_[初级]_[std::vector的多线程读写问题]
- C++(5)指针
- C++(4)数组
- C++(3)标准库类型
- eclipse报错lib32stdc++6
- C++(2)基本数据类型
- C++(1)入门
- 链表实现队列 c语言
- 一致性hash算法 C++语言实现
- [C++11 并发编程] 03 - 向线程传递参数
- redhat下配置c++开发环境
- c++中的构造函数和析构函数
- C 语言和C++语言的 struct对比
- 详细解析C语言中的开方实现
- C语言,C++,static
- C++ 锁,socket死锁
- C++的输入输出
- 【C/C++】String类实现
- Google代码规范工具Cpplint的使用