Concatenate string into C

Asked

Viewed 36 times

-2

Good afternoon guys, I’m starting my studies in c and I found a problem trying to concatenate strings.

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

int main ()
{
    char str1[50], str2[50], str3[50];
    
    printf ("Digite a primeira frase:");
    fgets (str1, 50, stdin);

    printf ("Digite a segunda frase:");
    fgets (str2, 50, stdin);
    
    strcat (str1, str2);
    
    printf ("Frases concatenadas: %s ", str1);
    
}

At the end the program prints the \n of the first string, so the result comes out as with the second string on a separate line, rather than one after the other, how to solve this?

  • Study the definition of the fgets function which will find that the or it will consider the maximum number of discriminated characters in the function call or will consider the ' n' character as being part of the string. One possibility is to override the ' n' com character: str1[strlen(str1) - 1] = '\0';.

1 answer

0

The function fgets reads the string until the number of characters is read or until a new line (\n) or EOF to be found. If it finds a new line character, it adds it to the String.

You have two options:

  • You can use another reading function (for example fscanf) and adapt the code for her.

  • Insert the string ending character exactly where the new line character is. This should be done before concatenating the two. One way to do this is:

string1[ strcspn( str1, "\n" ) ] = '\0';
string1[ strcspn( str2, "\n" ) ] = '\0';
strcat (str1, str2);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.