-1

I have written this code but it's not working. It is showing some extra characters in the end. Here's the code:

// Program to concate/join two string
#include<stdio.h>
#include<string.h>
main()
{
    int i,j,n=0;
    char str[100],str2[100],str3[100];
    printf("Enter string 1:\n");
    gets(str);
    printf("Enter string 2:\n");
    gets(str2);
    for(i=0;str[i]!='\0';i++)
    {
        str3[i]=str[i];
        n=n+1;
    }
    for(i=0,j=n;str2[i]!='\0';i++,j++)
    {
        str3[j]=str2[i];
    }
    printf("The concanted sring is: \n");
    puts(str3);
}

Here's the output

Pablo
  • 13,271
  • 4
  • 39
  • 59
Marcus
  • 1

3 Answers3

1

In C language, a string is a null-terminated array of characters.

It is showing some extra characters in the end.

Reason for this is that you are not adding null character at the end of string str3 after concatenating str2 to it. Add a null-character at the end of the concatenated string, like this:

str3[j] = '\0';

Also, you should not use gets(). It has been obsoleted. Instead, use fgets().


Additional:
Follow the good programming practice, make a habit of specifying int as the return type of main function.

H.S.
  • 11,654
  • 2
  • 15
  • 32
1

Terminate the str3 string with '\0' after you finish the copy loop:

for(i=0,j=n;str2[i]!='\0';i++,j++)
{
    str3[j]=str2[i];
}
str3[j] = '\0';  // proper termination of the `str3`.

Otherwise the str3will continue till first random '\0' in the memory is encountered. That is why you get extra characters when you print str3.

Also read this: gets() function in C and

Why is the gets function so dangerous that it should not be used?

Avoid gets() in your programs!

sg7
  • 6,108
  • 2
  • 32
  • 40
0

You can use one of best string manipulation function "strcat()" to concatenate to strings easily. try using below solution :

#include <stdio.h>
#include <string.h>
int main()
{
    char str1[] = "Hello" , str2[] = "There";

    //concatenates str1 and str2 and resultant string is stored in str1.

    strcat(str1,str2);

    puts(str1);    
    puts(str2); 

    return 0;
}

Output: HelloThere

There

Ganesh Sanap
  • 1,386
  • 1
  • 8
  • 18