0

So I'm trying to concatenate two strings but in the output the second string appears on the next line. I want them to be on the same line.

#include <string.h>
#include <stdio.h>
int main()
{
    char str1[50], str2[50];
    fgets(str1, sizeof(str1), stdin);
    fgets(str2, sizeof(str2), stdin);
    strcat(str1, str2);
    printf("%s", str1);
    return 0;
}

`

  • `fgets` doesn't remove the trailing newline from the string in input. Ps: even if it is not related to your issue, you concat `str2` to `str1` but the latter might not have enough space: what if both the acquired strings are 49 bytes long? The resulting string would be `49*2+1 = 99` bytes long, that won't fit in `str1`. – Roberto Caboni Oct 11 '20 at 06:37

1 Answers1

0

The problem is not on strcat, this is fgets which keep the ending '\n' at the end of the string.

To remove this character I suggest you: Removing trailing newline character from fgets() input

Robert
  • 2,711
  • 7
  • 15