Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is fgets call ignored if input is of specific size and format?

Tags:

c

string

I have the following code written in C

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

int main(void)
{
    char buf1[8];
    char buf2[1024];
    int n;

    fgets(buf1, 6, stdin);
    n = atoi(buf1);

    fgets(buf2, 16, stdin);

    return 0;
}

Whenever an input with length of more than 4 characters is given to the first fgets, the second fgets exists without waiting for input.

If the first input = 1000, the second fgets hangs and waits for input. However, if the input has 5 characters, 10000 for example, the second fgets exists and the program finishes.

What is the explanation for this behaviour?

like image 342
anegru Avatar asked Mar 04 '23 03:03

anegru


1 Answers

If the input exceeds the specified size minus 1 in a call of fgets as for example

char buf1[8];

fgets(buf1, 8, stdin);

and the input is

1234567

then the new line character '\n' that corresponds to the pressed Enter key is not read from the input buffer.

The character array f1 will contain the following content

{ '1', '2', '3', '4', '5', '6', '7', '\0' }

So the input buffer stays non-empty and the second call of fgets reads the tail of the input buffer without waiting one more user input.

When the input is less than the specified size minus 1 then the new line character '\n' is read into the character array and the input buffer will be empty.

For example if for this call

fgets(buf1, 8, stdin);

the user enters

123456

then the character array will contain

{ '1', '2', '3', '4', '5', '6', '\n', '\0' }
like image 56
Vlad from Moscow Avatar answered Mar 05 '23 17:03

Vlad from Moscow