!!!c_str()就是将C++的string轉化為C的字元串數組!!!
C中沒有string,是以函數c_str()就是将C++的string轉化為C的字元串數組,c_str()生成一個const char *指針,指向字元串的首位址。
下文通過3段簡單的代碼比較分析,具體說明c_str()的使用方法和注意事項。
用法一:
首先看一段代碼:
#include <iostream>
#include <string>
using namespace std;
int main()
{
const char *c;
string s = "1234";
c = s.c_str(); //c最後指向的内容是垃圾,因為當s對象被析構,其内容被處理,
//同時,編譯器也将報錯——将一個const char *賦與一個char *。
//是以要麼現用現轉換,要麼把它的資料複制到使用者自己可以管理的記憶體中
cout<<c<<endl;
s = "abcd";
cout<<c<<endl;
system("pause");
}
結果是:
1234
abcd
如果程式中繼續使用c指針,導緻的錯誤是不可預估的。比如:1234變成abcd
用法二:
使用strcpy()函數 等來操作方法c_str()傳回的指針 。
更好處理為:
#include <iostream>
#include <string>
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;
system("pause");
}
結果是:
1234
1234
用法三:
再舉個例子
c_str()以char*形式傳回string内含字元串
如果一個函數要求char*參數,可以使用c_str()方法:
string s = "Hello World!";
printf("%s", s.c_str()); //輸出 "Hello World!"
system("pause");
結果是:
Hello World!
參考資料:
- C++ c_str() 用法 ↩︎ ↩︎
- c++中c_str()的用法詳解 ↩︎