(內容摘自網路,自己整理)
const char* c_str ( ) const;
string::c_strpublic member function const char* c_str ( ) const;
Get C string equivalent
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
標準標頭檔<cstring>包含操作c-串的函數庫。這些庫函數表達了我們希望使用的幾乎每種字串操作。 當調用庫函數,客戶程式提供的是string型別參數,而庫函數內部實現用的是c-串,因此需要將string對象,轉化為char*對象,而c_str()提供了這樣一種方法,它返回const char*類型(可讀不可改)的指向字元數組的指標。 例:
#include <iostream>
#include <string.h>
using namespace std;
int main(void) {
string add_to = "hello!";
const string add_on = "baby";
const char *cfirst = add_to.c_str();
const char *csecond = add_on.c_str();
char *copy = new char[strlen(cfirst) + strlen(csecond) + 1];
strcpy(copy, cfirst);
strcat(copy, csecond);
add_to = copy;
cout << "copy: " << copy << endl;
delete [] copy;
cout << "add_to: " << add_to << endl;
return 0;
}
輸出:
copy: hello!baby
add_to: hello!baby
注意:
_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對象被析構,其內容被處理(糾正:s對象的析構是在對指標c完成賦值操作之後進行的,故此處並沒有錯誤)
在vc++2010中提示的錯誤原因: Error:不能將"const char*”型的值分配到"char*"類型的實體。
應該這樣用:
char c[20];
string s="1234";
strcpy(c,s.c_str());
這樣才不會出錯,c_str()返回的是一個臨時指標,不能對其進行操作