1. 程式人生 > 其它 >08s.c_str()與strcpy(c,s.c_str());

08s.c_str()與strcpy(c,s.c_str());

//標準庫的string類提供了三個成員函式來從一個string得到c型別的字元陣列
//主要介紹c_str
//c_str():生成一個const char*指標,指向以空字元終止的陣列。
//這個陣列應該是string類內部的陣列
#include <iostream>
//需要包含cstring的字串
#include <cstring>
using namespace std;
 
int main()
{
    //string-->char*
    //c_str()函式返回一個指向正規C字串的指標, 內容與本string串相同
 
    //這個陣列的資料是臨時的,當有一個改變這些資料的成員函式被呼叫後,其中的資料就會失效。
    //因此要麼現用先轉換,要麼把它的資料複製到使用者自己可以管理的記憶體中
    const char *c;
    string s = "1234";
    cout<<s<<endl;
    c = s.c_str();
    cout<<c<<endl;

    s = "abcde";
    cout<<s<<endl;
    cout<<c<<endl;
}

/*
1234
1234
abcde
abcde
*/

/*
其實上面的c = s.c_str(); 
不是一個好習慣。既然c指標指向的內容容易失效,我們就應該按照上面的方法,
那怎麼把資料複製出來呢?這就要用到strcpy等函式(推薦)。
*/



//標準庫的string類提供了三個成員函式來從一個string得到c型別的字元陣列
//主要介紹c_str
//c_str():生成一個const char*指標,指向以空字元終止的陣列。
//這個陣列應該是string類內部的陣列
#include <iostream>
//需要包含cstring的字串
#include <cstring>
using namespace std;
 
int main()
{
    //更好的方法是將string陣列中的內容複製出來 所以會用到strcpy()這個函式
    char *c = new char[20];
    string s = "1234";
    // c_str()返回一個客戶程式可讀不可改的指向字元陣列的指標,不需要手動釋放或刪除這個指標。
    strcpy(c,s.c_str());
    cout<<c<<endl;
    s = "abcd";
    cout<<c<<endl;
}
/*
1234
1234
*/