c_str()函数:
string.c_str是Borland封装的String类中的一个函数,它返回当前字符串的首字符地址;
c_str函数的 返回值是const char*的,不能直接赋值给char*;
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
代码示例:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str="Hello ";
const char *b=str.c_str();//必须为const char*
//char *a=str.c_str();//错误
cout<<b<<endl;//只输出 Hello
str+="World";
cout<<b<<endl;
//printf("%s\n",str);//输出错误
printf("%s\n",str.c_str());//正确
system("pause");
return 0;
}
运行结果: