title: How to prevent fgets() from picking \n as input?
body: <p>The book_name is picking \n as input a printing the next variable in a new line. I inserted this code <code>while ((getchar()) != '\n');</code> to prevent fgets() from taking \n as input after using scanf(). But i can't understand why fgets() is taking \n as input. Please explain.</p>
  <p><em><strong>CODE</strong></em></p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  
  typedef struct {
      int id;
      char *book_name;
      char *author;
  } book;
  
  int main() {
      int n;
  
      printf(&quot;Enter number of books: \n&quot;);
      scanf(&quot;%d&quot;, &amp;n);
  
      book *bk = calloc(n, sizeof(book));
  
      for (int i = 0; i &lt; n; i++)
      {
          printf(&quot;Enter the no of the book: \n&quot;);
          scanf(&quot;%d&quot;, &amp;((bk+i)-&gt;id));
  
          while ((getchar()) != '\n');
  
          (bk+i)-&gt;book_name = malloc(20);
          printf(&quot;Enter the name of the book: \n&quot;);
          fgets((bk+i)-&gt;book_name, 20, stdin);
  
          (bk+i)-&gt;author = malloc(20);
          printf(&quot;Enter the author of the book: \n&quot;);
          fgets((bk+i)-&gt;author, 20, stdin);
      }
  
      for (int i = 0; i &lt; n; i++)
      {
          printf(&quot;%d %s %s\n&quot;, (bk+i)-&gt;id, (bk+i)-&gt;book_name, (bk+i)-&gt;author);
      }
      
      
      return 0;
  }
  </code></pre>
  <p><em><strong>OUTPUT</strong></em></p>
  <p><a href="https://i.stack.imgur.com/03I4B.png" rel="nofollow noreferrer">Output of code</a></p>