Function strcat appends its second argument (a string) to its first argument (a character array containing a string). The first character of the second argument replaces the null character (' '
) that terminates the string in the first argument. You must ensure that the array used to store the first string is large enough to store the combination of the first string, the second string and the terminating null character (copied from the second string). Function strncat appends a specified number of characters from the second string to the first string and appends a terminating null character to the result. The program of Fig. 20.23 demonstrates function strcat
(lines 15 and 25) and function strncat
(line 20).
1 // Fig. 20.23: fig20_23.cpp
2 // Using strcat and strncat.
3 #include <iostream>
4 #include <cstring> // prototypes for strcat and strncat
5 using namespace std;
6
7 int main()
8 {
9 char s1[ 20 ] = "Happy "; // length 6
10 char s2[] = "New Year "; // length 9
11 char s3[ 40 ] = "";
12
13 cout << "s1 = " << s1 << "
s2 = " << s2;
14
15 strcat( s1, s2 ); // concatenate s2 to s1 (length 15)
16
17 cout << "
After strcat(s1, s2):
s1 = " << s1 << "
s2 = " << s2;
18
19 // concatenate first 6 characters of s1 to s3
20 strncat( s3, s1, 6 ); // places ' ' after last character
21
22 cout << "
After strncat(s3, s1, 6):
s1 = " << s1
23 << "
s3 = " << s3;
24
25 strcat( s3, s1 ); // concatenate s1 to s3
26 cout << "
After strcat(s3, s1):
s1 = " << s1
27 << "
s3 = " << s3 << endl;
28 } // end main
s1 = Happy
s2 = New Year
After strcat(s1, s2):
s1 = Happy New Year
s2 = New Year
After strncat(s3, s1, 6):
s1 = Happy New Year
s3 = Happy
After strcat(s3, s1):
s1 = Happy New Year
s3 = Happy Happy New Year