strcat() vs strncat() in C++

C++ProgrammingServer Side Programming

Both strcat() and strncat() are predefined string functions in C++. Details about these are given as follows.

strcat()

This function is used for concatenation. It appends a copy of the source string at the end of the destination string and returns a pointer to the destination string. The syntax of strcat() is given as follows.

char *strcat(char *dest, const char *src)

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

Example

 Live Demo

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

Output

The concatenated string is Mangoes are yellow

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

char str1[20] = "Mangoes are ";
char str2[20] = "yellow";
strcat(str1, str2);
cout << "The concatenated string is "<<str1;

strncat()

This function is also used for concatenation like strcat(). 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 );

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

Example

 Live Demo

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

Output

The concatenated string is Mangoes are yell

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

char str1[20] = "Mangoes are ";
char str2[20] = "yellow";
strncat(str1, str2, 4);
cout << "The concatenated string is "<<str1;
raja
Published on 05-Oct-2018 13:19:27
Advertisements