Concatenating strings in C. newline in output

Viewed 1831

I have strange problem where the output of the concatenation comes with a new line between each string input. I tried couple of different things eg. removing the dynamic memory allocation, copying strings into one another and then concatenating. the same issue is there. any ideas why?

Input:

> one
> two

Output:

> Result of concatenation: one
> two

here is the code

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


int main(int argc, char const *argv[])
{
    /* code */

    char string1[100];
    char string2[100];
    char *concat;

    fgets(string1,100,stdin);
    fgets(string2,100,stdin);

    unsigned int size = strlen(string1) + strlen(string2);

    concat = (char *) malloc(sizeof(char) * size);

    if (concat==NULL)
    {
        exit(0); 
    }

    strcat(concat,string1);
    strcat(concat,string2);

    printf("Result of concatenation: %s",concat);
    return 0;
}

2 Answers

For starters the function fgets can append the new line character to the entered strings. You should remove it. For example

fgets(string1,100,stdin);
string1[ strcspn( string1, "\n" ) ] = '\0';
fgets(string2,100,stdin);
string2[ strcspn( string2, "\n" ) ] = '\0';

Secondly you forgot about the terminating zero when was allocating memory. Instead of

unsigned int size = strlen(string1) + strlen(string2);

You have to write

size_t size = strlen(string1) + strlen(string2) + 1;

Futhermore the allocated memory is not initislaized. You have to write

concat[0] = '\0';

before these statements

strcat(concat,string1);
strcat(concat,string2);

And do not forget to free the allocated memory.

free( concat );

From the man page:

char *fgets(char *restrict s, int n, FILE *restrict stream);

...

The fgets() function shall read bytes from stream into the array pointed to by s, until n−1 bytes are read, or a <newline> is read and transferred to s, or an end-of-file condition is encountered. The string is then terminated with a null byte.

You are likely including the \n (new line characters) read by fgets in your concatenated array of characters.

Related