Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Problem with scanf() when there is fgets()/gets()/scanf() after it in C
In C programming, a common issue occurs when using scanf() followed by fgets(), gets(), or another scanf() for character input. The problem arises because scanf() leaves a newline character in the input buffer, which interferes with subsequent input functions.
Syntax
scanf("format_specifier", &variable);
fgets(string, size, stdin);
Problem 1: scanf() Followed by fgets()
When scanf() reads an integer and is followed by fgets(), the newline character left by scanf() is immediately consumed by fgets() −
#include <stdio.h>
int main() {
int x;
char str[100];
printf("Enter an integer: ");
scanf("%d", &x);
printf("Enter a string: ");
fgets(str, 100, stdin);
printf("x = %d, str = %s", x, str);
return 0;
}
Enter an integer: 30 Enter a string: x = 30, str =
Explanation: The fgets() reads the leftover newline character instead of waiting for user input, resulting in an empty string.
Solution: Using getchar() to Clear Buffer
#include <stdio.h>
int main() {
int x;
char str[100];
printf("Enter an integer: ");
scanf("%d", &x);
getchar(); /* Clear the newline character */
printf("Enter a string: ");
fgets(str, 100, stdin);
printf("x = %d, str = %s", x, str);
return 0;
}
Enter an integer: 30 Enter a string: Hello World x = 30, str = Hello World
Problem 2: Multiple scanf() for Characters
When using scanf() repeatedly for character input, each scanf() leaves a newline that affects the next one −
#include <stdio.h>
int main() {
char a;
printf("Enter characters (q to quit):<br>");
do {
printf("Enter a character: ");
scanf("%c", &a);
printf("You entered: %c<br>", a);
} while (a != 'q');
return 0;
}
Enter characters (q to quit): Enter a character: a You entered: a Enter a character: You entered: Enter a character: q You entered: q
Solution: Using Space Before %c
#include <stdio.h>
int main() {
char a;
printf("Enter characters (q to quit):<br>");
do {
printf("Enter a character: ");
scanf(" %c", &a); /* Space before %c skips whitespace */
printf("You entered: %c<br>", a);
} while (a != 'q');
return 0;
}
Enter characters (q to quit): Enter a character: a You entered: a Enter a character: b You entered: b Enter a character: q You entered: q
Key Points
-
scanf()leaves whitespace characters (including newline) in the input buffer. - Use
getchar()or a space before format specifiers to clear the buffer. - For character input, use
scanf(" %c", &variable)with a leading space. - Consider using
fgets()for string input instead of mixingscanf()andfgets().
Conclusion
Buffer management is crucial when mixing different input functions in C. Always clear leftover characters using getchar() or format specifiers with leading spaces to ensure proper input handling.
