< previous page page_242 next page >

Page 242
LISTING 15.9 continued
d5ef64f4d3250b96ba5c07ca5bbc2f56.gif
 4:    {
 5:       const int MaxLength = 80;
 6:       char String1[] = No man is an island;
 7:       char String2[MaxLength+1];
 8:
 9:
10:       strncpy(String2,String1,MaxLength);
11:       String2[strlen(String1)] = \0
12:       cout << String1:  << String1 << endl;
13:       cout << String2:  << String2 << endl;
14:       return 0;
15:    }

Output:
String1: No man is an island
String2: No man is an island
Analysis: In line 10, the call to strcpy() has been changed to a call to strncpy(), which takes a third parameter: the maximum number of characters to copy. The buffer String2 is declared to take MaxLength+1 characters. The extra character is for the null, which must terminate the string.
String Classes
Most C++ compilers come with a class library that includes a large set of classes for data manipulation. A standard component of a class library is a String class.
C++ inherited the null-terminated string and the library of functions that includes strcpy() from C, but these functions aren't integrated into an object-oriented framework. A String class 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 String class.
If your compiler doesn't already provide a String class (and perhaps even if it does), you might want to write your own.
At a minimum, a String class should overcome the basic limitations of character arrays. Like all arrays, character arrays are static. You define how large they are. They always take up that much room in memory, even if you don't need it all. Writing past the end of the array is disastrous.
A good String class allocates only as much memory as it needs and always enough to hold whatever it is given. If it can't allocate enough memory, it should fail gracefully.

 
< previous page page_242 next page >

If you like this book, buy it!