strcat() function in C++

In this guide, you will learn what is strcat() function is in C++ programming and how to use it with an example.

1. strcat() Function Overview

The strcat() function in C++ is used to concatenate (or append) one string to the end of another. It is a part of the <cstring> header. This function becomes useful when you need to join two strings together into a single string.

Signature:

char* strcat(char* destination, const char* source);

Parameters:

- destination: Pointer to the destination string to which the source string will be appended.

- source: String to be appended to the destination string.

2. Source Code Example

#include <iostream>
#include <cstring>

int main() {
    char destination[50] = "C++ ";
    char source[] = "Programming";

    // Using strcat to concatenate source to destination
    strcat(destination, source);

    std::cout << "Concatenated string: " << destination;
    return 0;
}

Output:

Concatenated string: C++ Programming

3. Explanation

In the provided source code:

1. The necessary header files are included: <iostream> for input/output operations and <cstring> for strcat().

2. Two character arrays, destination and source, are defined. The destination array is initialized with the string "C++ " while the source array is initialized with "Programming".

3. The strcat() function is then used to append the contents of source to destination.

4. The concatenated string in destination is printed to the screen.


Comments