C++ 一个例子说明.c_str()函数

atoi()是C语言中的字符串转换成整型数的一个函数,在例子的代码里面会用到,其函数原型为:

int atoi(const char *nptr);

下面是一个C语言的代码,可以正常运行:

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。
#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()); }
扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄