1.标准库中的string类提供了3个成员函数来从一个string得到c类型的字符数组:
c_str()
data()
copy(p,n)
2.c_str()
是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址。换种说法,c_str()
函数返回一个指向正规C字符串的指针常量,内容与本string串相同。这是为了与C语言兼容,在C语言中没有string类型,故必须通过string类对象的成员函数c_str()
把string对象转换成C中的字符串样式。
3.c_str()
函数返回一个指向正规C字符串的指针常量,内容与本string串相同。
4.c_str()
函数原型是:const char*c_str() const;
5.c_str()
生成一个const char*指针,指向以空字符终止的数组。data()
与c_str()
类似,但是返回的数组不以空字符终止。
6.注意:一定要使用strcpy()等函数来操作c_str()
返回的指针。例如下面这样写是错误的:
char *c;
string s="1234";
c=s.c_str();
上述代码中,c最后指向的内容是垃圾,因为s对象被析构,其内容被处理,同时编译器会报错,正确代码如下:
char *cstr, *p;
string str("Please split this phrase into tokens");
cstr = new char[str.size() + 1];//str.size()仅仅是字符的长度
strcpy(cstr, str.c_str());
原型声明:extern char *strcpy(char *dest,char *src);
7.如果一个函数要求char*参数,可以使用c_str()
方法。
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。这也解释了前文用strcpy(char*dest, char *str)
将c_str()
函数返回值保存在dest指向的一片区域中。
const _Elem *c_str() const
{ // return pointer to null-terminated nonmutable array
return (_Myptr());
}
原文
https://blog.csdn.net/deeplan_1994/article/details/88782015