I'm trying to implement strcat() in C but stuck on that the output result is repeated src.
here is my code.
void my_strcat(char des[], char src[]) {
int i = 0, j = 0;
while (des[i] != '\0')
i += 1;
while (src[j] != '\0') {
des[i + j] = src[j];
j += 1;
}
des[i + j] = '\0';
printf("%s", des);
}
int main() {
char des[1000], src[100];
for(int i = 0; i < 2; ++i) {
printf("src: ");
scanf("%s", src);
my_strcat(des, src);
}
printf("%s", des);
}
the output is not the same as I was expected before. It's like for example:
src: a src: b des: aabb
You probably want this:
#include <stdio.h>
#include <stdlib.h>
void my_strcat(char des[], const char src[]) { // better use const her
int i = 0, j = 0;
while (des[i] != '\0')
i += 1;
while (src[j] != '\0') {
des[i + j] = src[j];
j += 1;
}
des[i + j] = '\0';
// printf("%s", des); // dont print des here
}
int main() {
char des[1000];
char src[100];
des[0] = 0; // initialize des to a zero length string
for (int i = 0; i < 2; ++i) {
printf("src: ");
scanf("%s", src);
my_strcat(des, src);
}
printf("%s", des); // print the destination
}