Home > OS >  Unexpected line break in printf in c
Unexpected line break in printf in c

Time:11-16

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?

CodePudding user response:

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

  • Related