Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Error: strings getting unexpected output in C

/*write a program to insert a string into main string*/
#include <stdio.h>

int main()
{
    char text[100], str[20], ins_text[100];
    int i = 0, j = 0, k = 0, pos;
    printf("enter main text: ");
    gets(text);
    printf("enter string to be inserted: ");
    gets(str);
    printf("enter the position to be inserted: ");
    scanf("%d", &pos);

    while (text[i] != '\0')
    {
        if (i == pos)
        {
            while (str[k] != '\0')
            {
                ins_text[j] = str[k];
                j++;
                k++;
            }
        }
        else
        {
            ins_text[j] = text[i];
            j++;
        }
        i++;
    }

    ins_text[j] = '\0';
    printf("\n the new string is: ");
    puts(ins_text);
    return 0;
}

In the terminal

$ ./a.exe

enter main text: newsman
enter string to be inserted: paper
enter the position to be inserted: 4

The new string is: `newspaperan`

In final output above :- "the new string is : newspaperan" the letter "m" is missing.
I think it is due to post incrementing "j++" in while loop;
any way to fix it?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

That is the else that causes your problem. When you inserted the word in the middle you must continue as usual just after.

while (text[i] != '\0') {
    if (i == pos) { // insert the word
        while (str[k] != '\0') {
            ins_text[j++] = str[k++];
        }
    }
    ins_text[j++] = text[i++];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading