The C++ _Copy_s() (safer version) member function 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 the C++ _Copy_s() (safer version) member function to copy 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++ C++ _Copy_s() (safer version) member function to copy at most a specified number of characters from an indexed position in a source string to a target character array in C++ programming

 

// the C++ basic_string _Copy_s() example

#include <string>

#include <iostream>

using namespace std;

 

int main(void)

{

string str1("This is the str1 string");

basic_string<char>::iterator str_Iter;

 

// declare and initialize arrays with 0

const int array1_size = 20;

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 str1 string is: ";

for (str_Iter = str1.begin(); str_Iter != str1.end(); str_Iter++)

cout << *str_Iter;

cout<<endl;

 

basic_string<char>::size_type nArray1;

cout<<"\nOperation: str1._Copy_s(array1Ptr, array1_size, 12)"<<endl;

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;

cout<<"\nOperation: str1._Copy_s(array2Ptr, array2_size, 5, 6)"<<endl;

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 str1 string is: This is the str1 string

 

Operation: str1._Copy_s(array1Ptr, array1_size, 12)

The number of copied characters in array1 is: 12

The copied characters array1 is: This is the

 

Operation: str1._Copy_s(array2Ptr, array2_size, 5, 6)

The number of copied characters in array2 is: 5

The copied characters array2 is: s the

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index