源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

string中c_str(),data(),copy(p,n)函数的用法总结

  • 时间:2021-07-18 00:25 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:string中c_str(),data(),copy(p,n)函数的用法总结
标准库的string类提供了3个成员函数来从一个string得到c类型的字符数组:c_str()、data()、copy(p,n)。 1. c_str():生成一个const char*指针,指向以空字符终止的数组。 [b]注: ①[/b]这个数组的数据是临时的,当有一个改变这些数据的成员函数被调用后,其中的数据就会失效。因此要么现用先转换,要么把它的数据复制到用户自己可以管理的内存中。注意。看下例:
[u]复制代码[/u] 代码如下:
const char* c; string s="1234"; c = s.c_str();  cout<<c<<endl; //输出:1234 s="abcd"; cout<<c<<endl; //输出:abcd
上面如果继续用c指针的话,导致的错误将是不可想象的。就如:1234变为abcd 其实上面的c = s.c_str(); 不是一个好习惯。既然c指针指向的内容容易失效,我们就应该按照上面的方法,那怎么把数据复制出来呢?这就要用到strcpy等函数(推荐)。
[u]复制代码[/u] 代码如下:
//const char* c; //① //char* c;       //② //char c[20];  char* c=new char[20]; string s="1234"; //c = s.c_str();  strcpy(c,s.c_str()); cout<<c<<endl; //输出:1234 s="abcd"; cout<<c<<endl; //输出:1234
[b]注意:[/b]不能再像上面一样①所示了,const还怎么向里面写入值啊;也不能②所示,使用了未初始化的局部变量“c”,运行会出错的 。 [b]② [/b]c_str()返回一个客户程序可读不可改的指向字符数组的指针,不需要手动释放或删除这个指针。 2. data():与c_str()类似,但是返回的数组不以空字符终止。 3. copy(p,n,size_type _Off = 0):从string类型对象中至多复制n个字符到字符指针p指向的空间中。默认从首字符开始,但是也可以指定,开始的位置(记住从0开始)。返回真正从对象中复制的字符。------用户要确保p指向的空间足够保存n个字符。
[u]复制代码[/u] 代码如下:
// basic_string_copy.cpp // compile with: /EHsc /W3 #include <string> #include <iostream> int main( ) {     using namespace std;     string str1 ( "1234567890" );     basic_string <char>::iterator str_Iter;     char array1 [ 20 ] = { 0 };     char array2 [ 10 ] = { 0 };     basic_string <char>:: pointer array1Ptr = array1;     basic_string <char>:: 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.
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部