Consider below simple program in C. The program reads an integer using scanf(), then reads a string using fgets().
x = 10, str =
The problem with above code is scanf() reads an integer and leaves a newline character in buffer. So fgets() only reads newline and the string “test” is ignored by the program.
The similar problem occurs when scanf() is used in a loop.
a b q
......Enter q to quit...... Enter a character a Enter a character Enter a character b Enter a character Enter a character q
We can notice that above program prints an extra “Enter a character” followed by an extra new line. This happens because every scanf() leaves a newline character in buffer that is read by next scanf.
How to solve 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 extra space).
- We can add a getchar() after scanf() to read an extra newline.
This article is contributed by Dheeraj Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Cin-Cout vs Scanf-Printf
- scanf() and fscanf() in C - Simple Yet Poweful
- Inbuilt library functions for user Input | scanf, fscanf, sscanf, scanf_s, fscanf_s, sscanf_s
- Why "&" is not used for strings in scanf() function?
- Use of & in scanf() but not in printf()
- Difference between scanf() and gets() in C
- Why to use fgets() over scanf() in C?
- scanf("%[^\n]s", str) Vs gets(str) in C with Examples
- Return values of printf() and scanf() in C/C++
- Can we access global variable if there is a local variable with same name?
- How to use getline() in C++ when there are blank lines in input?
- Is there any need of "long" data type in C and C++?
- Is there any equivalent to typedef of C/C++ in Java ?
- Problem Solving on Storage Classes and Scoping of Variables
- Problem in comparing Floating point numbers and how to compare them correctly?
- Tr0ll 3 Walkthrough of Check the Flag or CTF Problem
- Functions that are executed before and after main() in C
- what happens when you don't free memory after using malloc()
- Types of C files after its compilation