This is my code
#include <stdio.h>
#include <conio.h>
#include <string.h>
int main()
{
char fn[20], ln[20], fulln[20];
int i, j, k;
printf("Enter your first name: ");
scanf("%s",fn);
printf("Enter your last name: ");
scanf("%s",ln);
for(i=0,k=0;fn[i]!='\0'; i++, k++)
{
fulln[k] = fn[i];
}
k++;
for(j=0;ln[j]!='\0';j++,k++)
{
fulln[k] = ln[j];
}
fulln[k] = '\0';
printf("Your full name is %s",fulln);
return 0;
}
Cannot understand what is wrong with it. It doesn't show the full name. I am using TDM-GCC-64(latest version)
Your code is basically doing a strcpy
and strcat
manually.
for(i=0,k=0;fn[i]!='\0'; i++, k++)
{
fulln[k] = fn[i];
}
k++;
for(j=0;ln[j]!='\0';j++,k++)
{
fulln[k] = ln[j];
}
fulln[k] = '\0';
There were problems with your code:
You should initialise all the char buffer, like this: char fn[20] = "", ln[20] = "", fulln[41] = "";
Also, you should make sure fulln
is big enough to contain both fn
and ln
. As an example, make it 41 as above, to accommodate a space in between.
Also, this line k++;
should be changed fulln[k++] = ' ';
- that adds the space in between.
Btw, as you already include string.h
there is no reason why you should not use the standard library strcpy
and strcat
. That means these two lines can replace your whole section of code:
strcpy(fulln, fn);
strcat(fulln, " ");
strcat(fulln, ln);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.