
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Problem with scanf When Using fgets and gets 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
#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
#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.