string中c_str()、data()、copy(p,n)函數的用法

標準庫的string類提供了3個成員函數來從一個string得到c類型的字符數組:c_str()、data()、copy(p,n)。

  1. c_str():生成一個const char*指針,指向以空字符終止的數組。

注:

①這個數組的數據是臨時的,當有一個改變這些數據的成員函數被調用後,其中的數據就會失效。因此要麼現用先轉換,要麼把它的數據複製到用戶自己可以管理的內存中。注意。看下例:
const char* c;
string s=”1234”;
c = s.c_str();
cout<

include

include

int main( )
{
using namespace std;
string str1 ( “1234567890” );
basic_string ::iterator str_Iter;
char array1 [ 20 ] = { 0 };
char array2 [ 10 ] = { 0 };
basic_string :: pointer array1Ptr = array1;
basic_string :: value_type *array2Ptr = array2;

cout << "The original string str1 is: ";
for ( str_Iter = str1.begin( ); str_Iter != str1.end( ); str_Iter++ )
    cout << *str_Iter;
cout << endl;

basic_string <char>:: size_type nArray1;
// Note: string::copy is potentially unsafe, consider
// using string::_Copy_s instead.
nArray1 = str1.copy ( array1Ptr , 12 );  // C4996
cout << "The number of copied characters in array1 is: "
    << nArray1 << endl;
cout << "The copied characters array1 is: " << array1Ptr << endl;

basic_string <char>:: size_type nArray2;
// Note: string::copy is potentially unsafe, consider
// using string::_Copy_s instead.
nArray2 = str1.copy ( array2Ptr , 5 , 6  );  // C4996
cout << "The number of copied characters in array2 is: "
    << nArray2 << endl;
cout << "The copied characters array2 is: " << array2Ptr << endl;

////注意一定要使array3有足夠的空間
//char array3[5]={0};
//basic_string<char>::pointer array3Ptr=array3;
//basic_string<char>::size_type nArray3;
//nArray3 = str1.copy(array3,9); //錯誤!!!!
//cout<<"The number of copied characters in array3 is: "
//  <<nArray3<<endl;
//cout<<"The copied characters array3 is: "<<array3Ptr<<endl;

}

上面最後註釋掉的部分,雖然編譯沒有錯誤,但是運行時會產生錯誤:Stack around the variable ‘array3’ was corrupted.

發佈了31 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章