Problem with scanf() when there is fgets()/gets()/scanf() after it in C


The problem states that what will be the working or the output if the scanf is followed by fgets()/gets()/scanf().

fgets()/gets() followed by scanf()

Example

 Live Demo

#include<stdio.h>
int main() {
   int x;
   char str[100];
   scanf("%d", &x);
   fgets(str, 100, stdin);
   printf("x = %d, str = %s", x, str);
   return 0;
}

Output

Input:
30
String
Output:
x = 30, str =

Explanation

fgets() and gets() are used to take string input from the user at the run time. I above code when we run enter the integer value then it won’t take the string value because when we gave newline after the integer value, then fgets() or gets() will take newline as an input instead of the desired input which is “String”.

scanf() followed by a scanf()

To repeatedly get scanf() followed by a scanf() we can use a loop.

Example

 Live Demo

#include<stdio.h>
int main() {
   int a;
   printf("enter q to quit");
   do {
      printf("
enter a character and q to exit");       scanf("%c", &a);       printf("%c
", a);    }while (a != ‘q’);    return 0; }

Output

Input:
abq
Output:
enter q to quit
enter a character and q to exita
a
enter a character and q to exit
enter a character and q to exitb
b
enter a character and q to exit
enter a character and q to exitq

Explanation

Here we can see an extra line ‘enter a character and q to exit’ after an extra new line, this is because each time scanf() leaves a newline character in a buffer which is being read by he next scanf() followed by it. To solve this problem with using ‘
’ with the type specifier in scanf() like scanf(“%c
”); or the other option is we can use extra getchar() or scanf() to read extra new line. 

Updated on: 23-Dec-2019

373 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements