The Program in C to concatenate two strings when user gives an input is given below:
#include <stdio.h>
#include <string.h>
int main() {
char str1[100], str2[100], result[200];
printf("Enter first string: ");
scanf("%s", str1);
printf("Enter second string: ");
scanf("%s", str2);
strcpy(result, str1);
strcat(result, str2);
printf("Concatenated string: %s\n", result);
return 0;
}
Output:
Enter first string: 23
Enter second string: 26
Concatenated string: 2326
Pro-Tips💡
This program uses the scanf
function to read in two strings from the user, and stores them in the str1
and str2
variables.
It then uses the strcpy
function to copy the contents of str1
into the result
variable, and the strcat
function to concatenate the contents of str2
to the end of result
.
Finally it prints the concatenated string which is stored in the result
variable.
You can also use the snprintf()
function to concatenate the strings.
snprintf(result, sizeof(result), "%s%s", str1, str2);
This function writes the concatenated string to the result
buffer, and it’s safe because it limits the number of characters to be written to the buffer to the size of the buffer.
Learn C-Sharp ↗
C-sharp covers every topic to learn about C-Sharp thoroughly.
Learn C Programming ↗
C-Programming covers every topic to learn about C-Sharp thoroughly.
Learn C++ Programming↗
C++ covers every topic to learn about C-Sharp thoroughly.