The C++ copy() 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() 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++ copy() 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++ copy() program example
#include <string>
#include <iostream>
using namespace std;
int main(void)
{
string str1("Testing the copy()");
basic_string <char>::iterator StrIter;
// declare and initialize arrays to 0
char Array1[20] = {0};
char Array2[10] = {0};
basic_string <char>:: pointer Array1Ptr = Array1;
basic_string <char>:: value_type *Array2Ptr = Array2;
// iterate character by character
cout<<"str1 string is: ";
for(StrIter = str1.begin(); StrIter != str1.end(); StrIter++)
cout<<*StrIter;
cout<<endl;
basic_string <char>::size_type NewArray1;
NewArray1 = str1.copy(Array1Ptr, 18); // C4996 warning, safer version: _Copy_s
cout<<"Operation: str1.copy(Array1Ptr, 18)"<<endl;
cout<<"The number of copied characters in Array1 is: "<<unsigned int(NewArray1)<<endl;
cout<<"Now, Array1 is: "<<Array1<<endl<<endl;
basic_string <char>::size_type NewArray2;
NewArray2 = str1.copy(Array2Ptr, 9, 2); // C4996 warning
cout<<"Operation: str1.copy(Array2Ptr, 9, 2)"<<endl;
cout<<"The number of copied characters in Array2 is: "<<unsigned int(NewArray2)<<endl;
cout<<"Now, Array2 is: "<<Array2Ptr<<endl;
return 0;
}
Output example:
str1 string is: Testing the copy()
Operation: str1.copy(Array1Ptr, 18)
The number of copied characters in Array1 is: 18
Now, Array1 is: Testing the copy()
Operation: str1.copy(Array2Ptr, 9, 2)
The number of copied characters in Array2 is: 9
Now, Array2 is: sting the
Press any key to continue . . .