1. 程式人生 > >c++ string中的c_str()與data()用法

c++ string中的c_str()與data()用法

#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; }

OUTPUT:

The original string object str1 is: Hello world
The length of the string object str1 = 11

The modified string object ptr1 is: Hello world
The length of character array str1 = 11

The C-style string c_str1 is: Hello world
The length of C-style string str1 = 11

所以兩個函式的區別到底是什麼???