Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

465
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!