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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值