The char_traits, _Copy_s() method C++ program example
Compiler: Visual C++ Express Edition 2005
Compiled on Platform: Windows XP Pro SP2
Header file: Standard
Additional library: none/default
Additional project setting: Set project to be compiled as C++
Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)
Other info: none
To do: Using C++ _Copy_s() which copies at most a specified number of characters from an indexed position in a source string to a target character array
To show: How to use the C++ _Copy_s() to copy at most a specified number of characters from an indexed position in a source string to a target character array
// basic_string _Copy_s()
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
string str1("Hello World");
// string iterator
basic_string<char>::iterator str_Iter;
// array's size
const int array1_size = 20;
// initialize all element to 0
char array1[array1_size] = { 0 };
const int array2_size = 10;
char array2[array2_size] = { 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;
nArray1 = str1._Copy_s(array1Ptr, array1_size, 12);
cout<<"The number of copied characters in array1 is: "
<<nArray1<<endl;
cout<<"The copied characters array1 is: "<<array1<<endl;
basic_string<char>:: size_type nArray2;
nArray2 = str1._Copy_s(array2Ptr, array2_size, 5, 6);
cout<<"The number of copied characters in array2 is: "
<<nArray2<<endl;
cout<<"The copied characters array2 is: "<<array2Ptr<<endl;
return 0;
}
Output example:
The original string str1 is: Hello World
The number of copied characters in array1 is: 11
The copied characters array1 is: Hello World
The number of copied characters in array2 is: 5
The copied characters array2 is: World
Press any key to continue . . .