0

I was looking into scanf() - shifts the cursor to next line so got curious if fgets does the same but the output I am getting does not make sense to me . Please help me out in understanding it

Code -

main()
{
char name[30] , name2[20];

scanf("%s" , name) ;
printf("%s" , name) ;
fgets(name2 , 30 , stdin) ;
printf("%s" , name2) ;

return 0 ;
}

Output - enter image description here

In the first line I input premier it gives an output of premier in second line but its not asking me for input second time and please clarify if fgets() also moves cursor to second line

THANKS FOR HELPING OUT!!!

  • By "shifts the cursor to next line", perhaps you mean ["consumes all available consecutive whitespace characters from the input"](https://en.cppreference.com/w/c/io/fscanf). `scanf()` will do that for `"%s "` (with a space), but not for `"%s"` (no space). – Fred Larson Feb 15 '21 at 18:35
  • `scanf` reads up to the newline character. `fgets` then reads it and thinks there’s nothing else to read. – Sami Kuhmonen Feb 15 '21 at 18:35
  • `scanf()` leaves a trailing newline character in the stream, later consumed by `fgets()`. Call `getchar()` after `scanf()` and it should be good to go for **this** case. – alex01011 Feb 15 '21 at 18:36
  • 1
    And note that `scanf("%s", name);` is no safer than [`gets()`](https://stackoverflow.com/q/1694036/10077), which should never be used. You'd be better off using `fgets()` for both inputs. – Fred Larson Feb 15 '21 at 18:41
  • 1
    Don't post pictures of text – klutt Feb 15 '21 at 19:34

2 Answers2

0

scanf() : This function scan value upto next white space or new line. fgets() : This function get value upto limit specified or new line.(include newline character)

In your code, first word/line scan by scanf it won't print on the terminal as printf function store it in the buffer. Next input gets by fgets command and printf function store its value also in the buffer. Once the program ends, the whole buffer printed on the terminal so your output is not expected. printf function only prints/flush data(clear buffer) if your program closed or new line comes.

Add "\n" in your program to get better understanding

#include <stdio.h>
int main()
{
   char name[30] , name2[20];

   scanf("%s" , name) ;
   printf("%s\n" , name) ;
   fgets(name2 , 30 , stdin) ;
   printf("%s" , name2) ;

   return 0 ;
}

Output :

./a.out
Scaning fget started
Scaning
 fget started
  • It could be any whitespace: ["Note that there is no difference between "\n", " ", "\t\t", or other whitespace in the format string."](https://en.cppreference.com/w/c/io/fscanf) – Fred Larson Feb 15 '21 at 19:48
0

The first scanf doesn't consume the end of line, just a string; so the call to fgets read an empty line.

Never mix scanf and fgets you will have problems. scanf is formatted input, while fgets is just raw input.

Jean-Baptiste Yunès
  • 34,548
  • 4
  • 48
  • 69