C++ 一个例子说明.c_str()函数
来源:互联网 发布:社交网络强弱关系 编辑:程序博客网 时间:2024/06/05 16:46
先举个例子说明一下:
atoi()
是C语言中的字符串转换成整型数的一个函数,在例子的代码里面会用到,其函数原型为:
int atoi(const char *nptr);
下面是一个C语言的代码,可以正常运行:
#include <stdio.h>#include <stdlib.h>int main(){ char *str = "123"; int num = atoi(str); printf("%d\n",num); getchar(); return 0;}
但是在C语言中使用字符串远远没有C++方便,毕竟C++提供了string类,把代码改成C++版:
//这是个错误的代码#include <iostream>#include <string>using namespace std;int main(){ string str ="123"; int num = atoi(str); cout<<num<<endl; getchar(); return 0;}
此时代码会报错,因为string与const char类型是不符的,前面提到,atoi()
是C语言提供的函数,而C语言中没有string类,字符串使用char指针来实现的。C与C++本身就是一家,为了让它们在一定程度上可以通用,就有了.c_str()
函数。我们只需要把代码修改成这样:
//这是个正确的代码#include <iostream>#include <string>using namespace std;int main(){ string str ="123"; int num = atoi(str.c_str()); cout<<num<<endl; getchar(); return 0;}
就是在string类型的str后面加上了.c_str()
函数,这也就是.c_str()
的作用: .c_str()
函数返回一个指向正规C字符串的指针常量, 内容与本string串相同。因为string类本身只是一个C++语言的封装,其实它的string对象内部真正的还是char缓冲区,所以.c_str()
指向了这个缓冲区并返回const。
const _Elem *c_str() const { // return pointer to null-terminated nonmutable array return (_Myptr()); }
阅读全文
1 0
- C++ 一个例子说明.c_str()函数
- string.c_str()函数说明
- 一个例子说明虚函数
- 说明JavaScript 函数间按值传参的一个例子
- C++string类的c_str()函数
- c_str函数
- c_str()函数
- c_str函数
- c_str函数
- c_str()函数
- c_str()函数
- c_str()函数
- c_str函数
- c_str()函数
- c_str函数
- c_str()函数
- c_str()函数
- C++ 函数指针 一个例子说明一下ing
- IT 行业加班到底有没有价值?
- 使用Spring 3的@value简化配置文件的读取
- Android
- 算法总结——八皇后问题(三种解法)
- LINUX中错误 SELinux is disabled
- C++ 一个例子说明.c_str()函数
- linux中创建图片服务器减轻传统服务器的压力
- 学习Nginx之理解正向代理和反向代理
- USB描述符
- Android中 字符串、byte数组、十六进制串、ASCII之间的相互转化
- 多线程下单例模式:懒加载(延迟加载)和即时加载
- zigbee 3.0 来袭,互联互通可期
- 注解方式定义的spring component打jar后,扫描失败的可能原因
- eclipse加载maven工程提示pom.xml无法解析org.apache.maven.plugins:maven-resources-plugin:2.4.3解决方案