VOOZH about

URL: https://www.geeksforgeeks.org/c/problem-with-using-fgets-gets-scanf-after-scanf-in-c/

⇱ Problem With Using fgets()/gets()/scanf() After scanf() in C - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Problem With Using fgets()/gets()/scanf() After scanf() in C

Last Updated : 23 Jul, 2025

scanf() is a library function in C. It reads standard input from stdin. fgets() is a library function in C. It reads a line from the specified stream and stores it into the string pointed to by the string variable. It only terminates when either:

  • end-of-file is reached
  • n-1 characters are read
  • the newline character is read

1) Consider a below simple program in C. The program reads an integer using scanf(), then reads a string using fgets(),

Input  

10
test

Output

x = 10, str = 

Explanation: The problem with the above code is scanf() reads an integer and leaves a newline character in the buffer. So fgets() only reads newline and the string "test" is ignored by the program.

2) The similar problem occurs when scanf() is used in a loop. 

Input:

a
b
q 

Output 

Press q to quit
Enter a character
a
Enter a character


Enter a character
b
Enter a character


Enter a character
q

Explanation: We can notice that the above program prints an extra "Enter a character" followed by an extra newline. This happens because every scanf() leaves a newline character in a buffer that is read by the next scanf.

How to Solve the Above Problem?  

  • We can make scanf() to read a new line by using an extra \n, i.e., scanf("%d\n", &x) . In fact scanf("%d ", &x) also works (Note the extra space).
  • We can add a getchar() after scanf() to read an extra newline.

The corrected programs for the above points will be,

1) scanf() when there is fgets() after it:

Input:

10
test

Output

x = 10, str = test

2) When scanf() is used in a loop: 

Input:

a
b
q 

Output: Press q to quit

Enter a character
a
Enter a character
b
Enter a character
q

Must Read: Problem occurs with Scanner in Java when nextLine() is used after nextXXX()
 

Comment