3
#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?

3
  • 2
    Did you read the documentation of fgets? If yes, read again carefully. If not: read carefully. Commented Jun 17, 2016 at 1:54
  • Advice on removing the newline that fgets puts in the buffer Commented Jun 17, 2016 at 2:24
  • "If I enter something with exactly 4 characters, the output is as I want" --> and the '\n' is waiting to be read by the next fgets() call. But the program ends first, Commented Jun 17, 2016 at 2:54

2 Answers 2

6

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 '.'.

Sign up to request clarification or add additional context in comments.

Comments

0

The issue is fgets() reads the newline char. You need to take out the newline character which is getting appended in you char array.

After fgets(str, sizeof(str), stdin); You can write below line to get rid of that newline character

str[strlen(str)-1]='\0'; or alternatively you can do like,

char * p=NULL;
p= strchr(str,'\n');
if(p!=NULL)
{
 *p='\0';
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.