- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
strcat() vs strncat() in C++
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
#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
#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;