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

CServer Side ProgrammingProgramming

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("\nenter a character and q to exit");
      scanf("%c", &a);
      printf("%c\n", 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 ‘\n’ with the type specifier in scanf() like scanf(“%c\n”); or the other option is we can use extra getchar() or scanf() to read extra new line. 

raja
Published on 23-Dec-2019 16:07:34
Advertisements