strncat() function in C++

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

1. strncat() Function Overview

The strncat() function in C++ is utilized to concatenate a specified number of characters from one string to the end of another. It's part of the <cstring> header. 

This function provides a safer way to concatenate strings as compared to strcat() since it allows for the specification of a maximum number of characters to be concatenated, preventing potential buffer overflows.

Signature:

char* strncat(char* destination, const char* source, size_t num);

Parameters:

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

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

- num: Maximum number of characters to be appended from the source string.

2. Source Code Example

#include <iostream>
#include <cstring>

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

    // Using strncat to concatenate the first 11 characters of source to destination
    strncat(destination, source, 11);

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

Output:

Concatenated string: C++ Programming

3. Explanation

1. We start by including the necessary header files: <iostream> for input/output operations and <cstring> for strncat().

2. Two character arrays, destination and source, are initialized. The destination array contains the string "C++ ", and the source array contains "Programming is fun!".

3. The strncat() function is invoked to append the first 11 characters of source to destination.

4. The result, stored in destination, is then printed.

By using strncat(), we can ensure a specified limit to the number of characters concatenated, adding a layer of safety against buffer overflows.


Comments