std::basic_string::copy
size_type copy( CharT* dest, size_type count, size_type pos = 0);
Copies a substring [pos, pos+count) to character string pointed to by dest. If the requested substring lasts past the end of the string, or if count == npos, the copied substring is [pos, size()). The resulting character string is not null-terminated.
If pos >= size(), std::out_of_range is thrown.
Parameters
dest pointer to the destination character string
pos position of the first character to include
count length of the substring
Return value
number of characters copied
example
1 #include <string> 2 #include <iostream> 3 4 using namespace std; 5 6 int main () 7 { 8 size_t length; 9 char buffer[8]; 10 string str("Test string......"); 11 12 length=str.copy(buffer,7,6); //从buffer6,往后数7个,相当于[ buffer[6], buffer[6+7] ) 13 buffer[length]='\0'; //加上'\0'使得buffer就到buffer[length]为止; 14 15 cout <<"buffer contains: " << buffer <<endl; 16 17 length=str.copy(buffer,str.size(),6); //从buffer6,往后数7个, 18 //相当于[ buffer[6], buffer[6+7] ) 19 buffer[length]='\0'; //使得buffer就到buffer[length]为止; 20 cout <<"buffer contains: " << buffer <<endl; 21 22 length=str.copy(buffer,7,0); //相当于[ buffer[0], buffer[7] ) 23 buffer[length]='\0'; 24 25 cout << "buffer contains: " << buffer <<endl; 26 27 length=str.copy(buffer,7); //缺省参数pos,默认pos=0; 28 //相当于[ buffer[0], buffer[7] ) 29 buffer[length]='\0'; 30 cout << "buffer contains: " << buffer <<endl; 31 length=str.copy(buffer,string::npos,6); //相当于[ buffer[7], buffer[npos] ) 32 //buffer越界赋值,没有出错 33 buffer[length]='\0'; 34 cout<<string::npos<<endl; //string::npos是4294967295 35 cout<<buffer[string::npos]<<endl; //实际是越界访问,但没有出错,输出空 36 cout<<buffer[length-1]<<endl; //实际是越界访问,但没有出错,输出了其他字符 37 cout << "buffer contains: " << buffer <<endl; 38 length=str.copy(buffer,string::npos); //相当于[ buffer[0], buffer[npos] ) 39 //buffer越界赋值,没有出错 40 buffer[length]='\0'; 41 cout << "buffer contains: " << buffer <<endl; //buffer越界 42 cout<<buffer[string::npos]<<endl; //越界访问,输出空 43 cout<<buffer[length-1]<<endl; //越界访问,没有输出str最后一个字符,输出了其他字符。 44 //到这里提示:buffer corrupt!! 45 return 0; 46 }