Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fgets() function atomatically breaking line when string is printed [duplicate]

#include <stdio.h>

void main () {
    char str[5];
    fgets(str, sizeof(str), stdin);
    printf("%s.", str);
}

I wrote this simple code in C, and I'm trying to print a string and a dot in a single line, but whenever I enter a string with 3 or less characters, the output has a line break after the string.

Input:

abc

Output:

abc
.

If I enter something with exactly 4 characters, the output is as I want, without the line break.

I've tried using the gets() and scanf() functions and they worked well, but I cannot use them.

Does someone know why it happens and a solution?

like image 701
Guilherme Uhrigshardt Avatar asked Jun 10 '26 11:06

Guilherme Uhrigshardt


1 Answers

The explanation to this issue is in the documentation of fgets:

Parsing stops if end-of-file occurs or a newline character is found, in which case str will contain that newline character.

That is precisely what happens in your case: str contains the input string "abc" followed by '\n', which gets printed between "abc" and dot '.'.

like image 140
Sergey Kalinichenko Avatar answered Jun 13 '26 01:06

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!