strncat() in C++

C++ProgrammingServer Side Programming

The function strncat() in C++ is used for concatenation. It appends the specified number of characters from the source string at the end of the destination string and returns a pointer to the destination string. The syntax of strncat() is given as follows.

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

In the above syntax, the source string src is appended at the end of the destination string dest till num characters only.

A program that demonstrates strcat() is given as follows.

Example

 Live Demo

#include <iostream>
#include <cstring>
using namespace std;
int main() {
   char str1[20] = "Programming is ";
   char str2[20] = "fun";
   strncat(str1, str2, 3);
   cout << "The concatenated string is "<<str1;
   return 0;
}

Output

The concatenated string is Programming is fun

In the above program, the two strings str1 and str2 are defined. strncat() appends the contents of str2 at the end of str1 till three characters and the concatenated string is displayed using cout. This is given as follows.

char str1[20] = "Programming is ";
char str2[20] = "fun";
strncat(str1, str2, 3);
cout << "The concatenated string is "<<str1;
raja
Published on 05-Oct-2018 13:23:21
Advertisements