In your code, you copy the null terminator of each string into the name
array, hence the final contents is "Alexander\0Graham\0Bell"
. printf
stops at the first null byte it finds in the string argument for %s
so only the first name is output.
You should instead use a separate index for the source and destination arrays and set a space between the 3 parts of the name.
Note also that you should tell scanf()
to stop reading after 14 bytes to avoid storing characters beyond the end of the arrays on overlong user input and test the return value to detect invalid input.
Here is a modified version:
#include <stdio.h>
int main() {
char fName[15], mName[15], lName[15], name[45];
int i, j;
printf("\nEnter the First name: ");
if (scanf("%14s", fName) != 1)
return 1;
printf("\nEnter the Middle name: ");
if (scanf("%14s", mName) != 1)
return 1;
printf("\nEnter the Last name: ");
if (scanf("%14s", lName) != 1)
return 1;
i = 0;
for (j = 0; fName[j] != '\0'; j++) {
name[i++] = fName[j];
}
name[i++] = ' ';
for (j = 0; mName[j] != '\0'; j++) {
name[i++] = mName[j];
}
name[i++] = ' ';
for (j = 0; lName[j] != '\0'; j++) {
name[i++] = lName[j];
}
name[i] = '\0';
printf("\nFull name is %s.\n", name);
return 0;
}
There is a simpler solution using string functions:
#include <stdio.h>
#include <string.h>
int main() {
char fName[15], mName[15], lName[15], name[45];
printf("\nEnter the First name: ");
if (scanf("%14s", fName) != 1)
return 1;
printf("\nEnter the Middle name: ");
if (scanf("%14s", mName) != 1)
return 1;
printf("\nEnter the Last name: ");
if (scanf("%14s", lName) != 1)
return 1;
strcpy(name, fName);
strcat(name, " ");
strcat(name, mName);
strcat(name, " ");
strcat(name, lName);
printf("\nFull name is %s.\n", name);
return 0;
}
And even simpler using just snprintf
:
#include <stdio.h>
int main() {
char fName[15], mName[15], lName[15], name[45];
printf("\nEnter the First name: ");
if (scanf("%14s", fName) != 1)
return 1;
printf("\nEnter the Middle name: ");
if (scanf("%14s", mName) != 1)
return 1;
printf("\nEnter the Last name: ");
if (scanf("%14s", lName) != 1)
return 1;
snprintf(name, sizeof name, "%s %s %s", fName, mName, lName);
printf("\nFull name is %s.\n", name);
return 0;
}