Managing Arrays and Strings 435
13
Using the strcpy()and strncpy()Methods ......................................................
A number of existing functions are available in the C++ library for dealing with strings.
C++ inherits many of these functions for dealing with C-style strings from the C lan-
guage. Among the many functions provided are two for copying one string into another:
strcpy()and strncpy(). strcpy()copies the entire contents of one string into a desig-
nated buffer. The other,strncpy()copies a number of characters from one string to
another. Listing 13.12 demonstrates the use of strcpy().
LISTING13.12 Using strcpy()
0: //Listing 13.12 Using strcpy()
1:
2: #include <iostream>
3: #include <string.h>
4: using namespace std;
5:
6: int main()
7: {
8: char String1[] = “No man is an island”;
9: char String2[80];
10:
11: strcpy(String2,String1);
12:
13: cout << “String1: “ << String1 << endl;
14: cout << “String2: “ << String2 << endl;
15: return 0;
16: }
String1: No man is an island
String2: No man is an island
This listing is relatively simple. It copies data from one string into another. The
header file string.his included on line 3. This file contains the prototype of the
strcpy()function. strcpy()takes two character arrays—a destination followed by a
source. On line 11, this function is used to copy String1into String2.
You have to be careful using the strcpy()function. If the source is larger than the desti-
nation,strcpy()overwrites past the end of the buffer. To protect against this, the
Standard Library also includes strncpy(). This variation takes a maximum number of
characters to copy. strncpy()copies up to the first null character or the maximum num-
ber of characters specified into the destination buffer. Listing 13.13 illustrates the use of
strncpy().
OUTPUT
ANALYSIS