What is strcat() in C++?
The strcat() method is a built-in C++ function that serves the purpose of concatenating (appending) one string at the end of another string. This function is defined in the cstring header file. Here’s a workflow example showing how it works:
C++ strcat() syntax
char *strcat(char *destination, const char *source);
The string source is appended at the end of destination. The function returns the pointer to destination. It’s important to ensure that destination has enough space to accommodate the concatenated result to avoid buffer overflow.
The strcat() function works well under certain conditions, which are important to keep in mind while working with this function:
Ensuring enough space: Make sure the destination array has enough space for both the existing content and the new content that needs to be appended. If it’s too small, the behavior is unpredictable.
Null-terminated strings: Both the destination and source must be pointers to null-terminated strings. That means they should end with a special character called the null character (
\0).
C++ strcat() code example
Here’s a code example showing the strcat() function works in C++:
#include <iostream>#include <cstring>using namespace std;int main(){char dest[50] = "John Works";char src[20] = " at Educative.";cout<<"Before Concatenation: "<<dest<<endl;strcat(dest, src);cout<<"After Concatenation: "<<dest<<endl;return 0;}
Code explanation
Line 2: We import the
cstringlibrary, which contains the implementation of thestrcat()function.Lines 7–8: We declare the
srcanddestcharacter arrays. It’s important to note that we have kept the size ofdestarray large enough so thatsrccan be appended at its end without resulting in buffer overflow.Line 11: Finally, we concatenate the string
srcat the end of stringdestusing thestrcat()function.
Free Resources