c_str

c_str

c_str是Borland封裝的String類中的一個函式,它返回當前字元串的首字元地址。當需要打開一個由用戶自己輸入檔案名稱的檔案時,可以這樣寫:ifstream in(st.c_str())。

基本介紹

  • 中文名:c_str
  • 特點:Borland封裝
  • 屬性:String類中的一個函式
  • 功能:返回當前字元串的首字元地址
c_str函式的返回值是constchar*的,不能直接賦值給char*,所以就需要我們進行相應的操作轉化,下面就是這一轉化過程。
c++語言提供了兩種字元串實現,其中較原始的一種只是字元串的c語言實現。與C語言的其他部分一樣,它在c++的所有實現中可用,我們將這種實現提供的字元串對象,歸為c-串,每個c-串char*類型的。
標準頭檔案<cstring>包含操作c-串的函式館。這些庫函式表達了我們希望使用的幾乎每種字元串操作。 當調用庫函式,客戶程式提供的是string類型參數,而庫函式內部實現用的是c-串,因此需要將string對象,轉化為char*對象,而c_str()提供了這樣一種方法,它返回const char*類型(可讀不可改)的指向字元數組指針。 例:
#include <iostream>
//#include <cstring>
#include <string> //使用頭檔案string ,否則最後cout<<無法輸出 add_to
using namespace std;
int main()
{
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;
}
resultresult
例(1)
函式聲明:const char *c_str();
c_str()函式返回一個指向正規C字元串的指針, 內容與本string串相同.
這是為了與c語言兼容,在c語言中沒有string類型,故必須通過string類對象的成員函式c_str()把string 對象轉換成c中的字元串樣式。
注意:一定要使用strcpy()函式 等來操作方法c_str()返回的指針
比如:最好不要這樣:

相關詞條

熱門詞條

聯絡我們