C++ strncat()

The strncat() function in C++ appends a specified number of characters of a string to the end of another string.

strncat() prototype

char* strncat( char* dest, const char* src, size_t count );

The strncat() function takes three arguments: dest, src and count. This function appends a maximum of count characters of the string pointed to by src the end of string pointed to by dest. The null terminating character at the end of dest is replaced by the first character of src and the resulting character is also null terminated.

The behaviour is undefined if

  • the strings overlap.
  • the dest array is not large enough to append the contents of src.

It is defined in <cstring> header file.

strncat() Parameters

  • dest: Pointer to a null terminating string to append to.
  • src: Pointer to a null terminating string that is to be appended.
  • count: Maximum numbers of characters to copy.

strncat() Return value

The strncat() function returns dest, the pointer to the destination string.

Example: How strncat() function works

#include <cstring>
#include <iostream>

using namespace std;

int main()
{
    char dest[50] = "Using strncat function,";
    char src[50] = " this part is added and this is ignored";

    strncat(dest, src, 19);
    
    cout << dest ;

    return 0;

}

When you run the program, the output will be:

Using strncat function, this part is added
Did you find this article helpful?