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:
strcat()
syntaxchar *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
).
strcat()
code exampleHere’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;}
Line 2: We import the cstring
library, which contains the implementation of the strcat()
function.
Lines 7–8: We declare the src
and dest
character arrays. It’s important to note that we have kept the size of dest
array large enough so that src
can be appended at its end without resulting in buffer overflow.
Line 11: Finally, we concatenate the string src
at the end of string dest
using the strcat()
function.
Free Resources