const char* c_str ( ) const;
将c++标准std string类转换为标准c的string格式 char * 类型,并将首地址返回, 地址从[0]开始算。
举例:
string testcstr = "Hello World";
const char *pch = testcstr.c_str();
cout<<pch<<endl;
cout<<pch[2]<<endl;
//打印结果为 Hello World
//l
char ch[20];
strcpy(ch, testcstr.c_str());
//strcpy需要 #include <string.h>
testat = "hahaha";
cout<<ch<<endl;
strcpy(ch, testcstr.c_str());
cout<<ch<<endl;
//打印结果为 Hello World
//hahaha
----------------------------------------
const char *c_str();c_str()函数返回一个指向正规C字符串的指针, 内容与本string串相同. 这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针 比如:最好不要这样: char* c; string s="1234"; c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理应该这样用: char c[20]; string s="1234"; strcpy(c,s.c_str()); 这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作再举个例子c_str() 以 char* 形式传回 string 内含字符串如果一个函数要求char*参数,可以使用c_str()方法: string s = "Hello World!";printf("%s", s.c_str()); //输出 "Hello World!"
----------------------------------------------------------------------------------
const char* c_str ( ) const;
Generates a null-terminated sequence of characters (c-string) with the same content as the string object and returns it as a pointer to an array of characters.
A terminating null character is automatically appended.
The returned array points to an internal location with the required storage space for this sequence of characters plus its terminating null-character, but the values in this array should not be modified in the program and are only guaranteed to remain unchanged until the next call to a non-constant member function of the string object.
Parameters
none
Return Value
Pointer to an internal array containing the c-string equivalent to the string content.
Example
| |
Output:
Please split this phrase into tokens |