Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

463
Visualizações
Unexpected line break in printf in c

I'm learning string in c, and i'm working on my homework which ask me to write a program to replace part of string under certain circumstances. Here is my source code(undone):

#include <stdio.h>
#include <string.h>
int main()
{
    char str1[128], str2[128], str3[128];
    for (int i = 0; i < 128; i++) //initialize str
    {
        str1[i] = 0;
        str2[i] = 0;
        str3[i] = 0;
    }
    printf("Input the first string:"); //inputs
    fgets(str1, 128, stdin);
    printf("Input the second string:");
    fgets(str2, 128, stdin);
    printf("Input the third string:");
    fgets(str3, 128, stdin);
    if (strncmp(str1, str2, strlen(str2) - 1) == 0) //if the first n charters match (n=length of str2)
    {
        printf("%s", str3); //print str3
        int RemainingChar = 0;
        RemainingChar = strlen(str1) - strlen(str2);
        for (int i = 0; i < RemainingChar; i++)
        {
            printf("%c", str1[i + strlen(str2) - 1]); //print the remaining part
        }
    }
    return 0;
}

Here is how it run:

Input the first string:asdfghjkl
Input the second string:asd
Input the third string:qwe
qwe
fghjkl

There is an unexpected line break. what should I do to make it output like this:qwefghjkl?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The function fgets will also store the newline character '\n' at the end of the line into the string. If you don't want this newline character to be printed, then you must remove it before printing the string.

See the following question for several ways to remove the newline character:

Removing trailing newline character from fgets() input

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda