C++ inherits from C a library of functions for dealing with strings. 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 designated buffer. Listing 15.8 demonstrates its use.
LISTING 15.8 USINGstrcpy()
1: #include <iostream.h>
2: #include <string.h>
3: int main()
4: {
5: char String1[] = No man is an island;
6: char String2[80];
7:
8: strcpy(String2,String1);
9:
10: cout << String1: << String1 << endl;
11: cout << String2: << String2 << endl;
12: return 0;
13: }
Output:
String1: No man is an island
String2: No man is an island
Analysis: The header file STRING.H is included in line 2. This file contains the prototype of the strcpy() function. strcpy() takes two character arraysa destination followed by a source. If the source were larger than the destination, strcpy() would overwrite 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 number of characters specified into the destination buffer.
Listing 15.9 illustrates the use of strncpy().
LISTING 15.9 USINGstrncpy()
1: #include <iostream.h>
2: #include <string.h>
3: int main()