#include <stdio.h>
#include <stdlib.h>

void main()
{
    char str[10],str1[10],str2[20];
    int i,j,k;
    printf("enter string1: ");
    gets(str1);
    printf("enter the  string 2: ");
    gets(str2);
    for(i=0,j=0;str1[i]!='\0';i++,j++)

    str[j]=str[i];

    for(i=0,k=j;str2[i]!='\0';i++,k++)

        str[k]=str2[i];



    printf("%s",str);
}

not producing correct output

Edited 4 Years Ago by rithish

str[j]=str[i];

That's not meaningful, but it's probably a typo where you clearly meant the right hand side to reference str1. However, that's evidence that very similar names are easy to mix up and result in subtle bugs.

You also neglect to terminate the destination string with a null character. And your code is awful. Even if you're using Turbo C, you don't have to write shit code using TurboC-isms. This will compile and run just peachy on your dinosaur of a compiler:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *safe_gets(char *buf, size_t size)
{
    if (!fgets(buf, size, stdin))
        return NULL;

    buf[strcspn(buf, "\n")] = '\0';

    return buf;
}

int main(void)
{
    char str[20], str1[10], str2[10];
    int i, k = 0;

    printf("Enter string 1: ");
    fflush(stdout);

    if (!safe_gets(str1, sizeof str1)) {
        fprintf(stderr, "Input error\n");
        return EXIT_FAILURE;
    }

    printf("Enter string 2: ");
    fflush(stdout);

    if (!safe_gets(str2, sizeof str2)) {
        fprintf(stderr, "Input error\n");
        return EXIT_FAILURE;
    }

    for (i = 0; str1[i] != '\0'; i++)
        str[k++] = str1[i];

    for (i = 0; str2[i] != '\0'; i++)
        str[k++] = str2[i];

    str[k] = '\0';

    printf("%s\n", str);

    return EXIT_SUCCESS;
}

or something like that

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

char *safe_gets(char *buf, size_t size)
{
    if (!fgets(buf, size, stdin))
        return NULL;

    buf[strcspn(buf, "\n")] = '\0';

    return buf;
}

int main(void)
{
    char str[7] = {0};
    int i, k = 0;
    int iLen = 0;
    printf("Enter string 1: ");
    fflush(stdout);

    if (!safe_gets(str, sizeof str)) {
        fprintf(stderr, "Input error\n");
        return EXIT_FAILURE;
    }

    printf("Enter string 2: ");
    fflush(stdout);
    iLen = strlen(str);
    if (!safe_gets(&str[iLen], sizeof str - iLen)) {
        fprintf(stderr, "Input error\n");
        return EXIT_FAILURE;
    }

    printf("\n%s\n", str);

    return EXIT_SUCCESS;
}
This article has been dead for over six months. Start a new discussion instead.