GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing www.tutorialspoint.com — C++ cstring strcat() Function
Selected Reading
C++ cstring strcat() FunctionThe C++ strcat() function is mainly used to concatenate two strings. This function is defined in cstring header file. We can make a single string out of two strings using the strcat() function. This function takes two arguments, the destination string and the source string. The source string is concatenated to the destination string. The destination string must have enough space to store the concatenated string. If the destination string is smaller than the concatenated string, it will cause a buffer overflow. SyntaxThe syntax of the C++ cstring strcat() function is − char *strcat(char *destination, const char *source); ParametersFollowing are the parameters of this function −
Return ValueThe strcat() function returns a single string which is the concatenated string of the destination and source strings. ExampleLet us understand how to use the C++ strcat() function with the help of an example. Here, we will try to concatenate two strings using the strcat() function. For this, we will create two strings, one source string and one destination string. We will then concatenate the source string to the destination string using the strcat() function. #include <iostream>
#include <cstring>
using namespace std;
int main() {
char source[] = "World!";
char destination[100] = "Hello, ";
// Concatenating the source string to destination string
strcat(destination, source);
cout << "Source: " << source << endl;
cout << "Destination: " << destination << endl;
return 0;
}
OutputWhen you run the program, the output will be: Source: World! Destination: Hello, World! Example 2Let's try another example where we set some conditions and based on that we will concatenate the strings. Now, consider a case where we have to check if string has vowels or not. If it has vowels, then will concatenate the string to the result string otherwise move to the next string. #include <iostream>
#include <cstring>
using namespace std;
bool hasVowels(char *str) {
for (int i = 0; str[i] != '\0'; i++) {
if (str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') {
return true;
}
}
return false;
}
int main() {
char str1[] = "Hello, ";
char str2[] = "World!";
char str3[] = "Sky";
char result[100] = "";
if (hasVowels(str1)) {
strcat(result, str1);
}
if (hasVowels(str2)) {
strcat(result, str2);
}
if (hasVowels(str3)) {
strcat(result, str3);
}
cout << "Result: " << result << endl;
return 0;
}
OutputWhen you run the program, the output will be: Result: Hello, World! Advertisements
|
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |