Sams Teach Yourself C++ in 21 Days

(singke) #1
LISTING13.13 Using strncpy()
0: //Listing 13.13 Using strncpy()
1:
2: #include <iostream>
3: #include <string.h>
4:
5: int main()
6: {
7: const int MaxLength = 80;
8: char String1[] = “No man is an island”;
9: char String2[MaxLength+1];
10:
11: strncpy(String2,String1,MaxLength);
12:
13: std::cout << “String1: “ << String1 << std::endl;
14: std::cout << “String2: “ << String2 << std::endl;
15: return 0;
16: }

String1: No man is an island
String2: No man is an island
Once again, a simple listing is presented. Like the preceding listing, this one sim-
ply copies data from one string into another. On line 11, the call to strcpy()has
been changed to a call to strncpy(), which takes a third parameter: the maximum num-
ber of characters to copy. The buffer String2is declared to take MaxLength+1characters.
The extra character is for the null, which both strcpy()and strncpy()automatically
add to the end of the string.

OUTPUT


436 Day 13


ANALYSIS

As with the integer array shown in Listing 13.9, character arrays can be
resized using heap allocation techniques and element-by-element copying.
Most flexible string classes provided to C++ programmers use some variation
on that technique to allow strings to grow and shrink or to insert or delete
elements from the middle of the string.

NOTE

String Classes ......................................................................................................


C++ inherited the null-terminated C-style string and the library of functions that includes
strcpy()from C, but these functions aren’t integrated into an object-oriented frame-
work. The Standard Library includes a Stringclass that provides an encapsulated set of
data and functions for manipulating that data, as well as accessor functions so that the
data itself is hidden from the clients of the Stringclass.
Free download pdf