Search code examples
cnewlinefgetsgets

generally gets() takes the input as \n which is at the end of printf() above it


Why does gets() ask for string here. I mean, why doesn't it consume the newline character from the previous printf() and the program just terminate? And yes i know i should use fgets() and stuff like that. Please don't mention about it.

code for reference-

#include <stdio.h>

main()
{
    char str[30];
    printf("\n");
    gets(str);
    puts(str);
}

Solution

  • From the manual of char *gets(char *str):

    Reads a line from stdin and stores it into the string pointed to by, str. It stops when either the newline character is read or when the end-of-file is reached, whichever comes first.

    From the manual for printf :

    The functions printf() and vprintf() write output to stdout, the standard output stream;

    As the manual mentions, gets reads a line from stdin.

    The function printf writes to stdout.

    Therefore gets won't read what printf is writing.