共用方式為


basic_string::c_str

轉換成字串的內容做為式的 C++., null 結尾的字串。

const value_type *c_str( ) const;

傳回值

要叫用之字串的 C-Style 版本的指標。指標值。呼叫非 const 的函式都無效,包括解構函式,在物件的 basic_string 的類別。

備註

屬於 C++ 樣板類別 basic_stringchar<> 不一定是以 null 終止的型別字串物件。 null 字元 (「\ 0 "當做屬性在 C++. -字串標記字串的結尾,但沒有特殊意義在型別字串物件,而且可以是字串的區段與其他字元。 將常數 char* 的自動轉換為字串,不過,字串類別不提供從 C-Style 字串的自動轉換為型別 **basic_string<char>**物件。

不應該修改,,因為這可能無法使用指標到字串,或者刪除傳回的 C-Style 字串,,因為字串具有有限的存留期和由類別字串所擁有。

範例

// basic_string_c_str.cpp
// compile with: /EHsc
#include <string>
#include <iostream>

int main( ) 
{
   using namespace std;

   string  str1 ( "Hello world" );
   cout << "The original string object str1 is: " 
        << str1 << endl;
   cout << "The length of the string object str1 = " 
        << str1.length ( ) << endl << endl;

   // Converting a string to an array of characters
   const char *ptr1 = 0;
   ptr1= str1.data ( );
   cout << "The modified string object ptr1 is: " << ptr1 
        << endl;
   cout << "The length of character array str1 = " 
        << strlen ( ptr1) << endl << endl;

   // Converting a string to a C-style string
   const char *c_str1 = str1.c_str ( );
   cout << "The C-style string c_str1 is: " << c_str1 
        << endl;
   cout << "The length of C-style string str1 = " 
        << strlen ( c_str1) << endl << endl;
}
  

需求

標頭:<string>

命名空間: std

請參閱

參考

basic_string 類別