Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

461
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda