Tushar Kamboj
Tushar Kamboj

Reputation: 47

Difficulty copying a single string in two substrings

I want to input a string and then make 2 substrings, first half in first string and second half in second string and if the string is odd then leave the middle element.

For input given as tushar, the output I am get is tus and an empty line.

Here is the code:

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

int main(void) {
    // your code goes here
    int t;
    scanf("%d", &t);
    while (t--) {
        char str[1000];
        int i, j;
        while ((getchar())!= '\n');
        scanf("%[^\n]s", str);
        int len = strlen(str);
        char first[(len / 2) + 1];
        char second[(len / 2) + 1];
        for (i = 0; i < (len / 2); i++) {
            first[i] = str[i];
            second[i] = str[(strlen(str)) - i];
        }
        printf("%s\n", first);
        printf("%s\n", second);
    }
    return 0;
}

Upvotes: 0

Views: 54

Answers (1)

Damien
Damien

Reputation: 4864

With your code, second[0] == '\0'. It corresponds to str[strlen(str)]. So the second string is seen as empty effectively.

There are two others issues:

  • We did not close the first string with '\0'.
  • For building the 2nd string, you are reading the input string from the end. I assume that it is not what you intend to do.
#include <stdio.h>
#include <string.h>
int main(void)
{
    // your code goes here
    int t;
    scanf("%d",&t);
    while(t--){
        char str[1000];
        int i,j;
        while((getchar())!= '\n');
        scanf("%s",str);
        int len = strlen(str);
        int position = (len + 1) / 2; 
        char first[(len/2)+1], second[(len/2)+1];
        for (i = 0; i < (len/2); i++)
        {
            first[i] = str[i];
            second[i] = str[position + i];
        }
        first[len/2] = '\0';
        second[len/2] = '\0';
        printf("%s\n",first);
        printf("%s\n",second);
    }
    return 0;
}

Upvotes: 1

Related Questions