标准库的string类提供了3个成员函数来从一个string得到c类型的字符数组:c_str()、data()、copy(p,n)。
- 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.