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
- Differentiate printable and control character in C ?
- rand() and srand() in C/C++
- Use of fflush(stdin) in C
- Operators in C / C++
- C/C++ Preprocessors
- Implementation of a Falling Matrix
- Code to generate the map of India (with explanation)
- Clearing The Input Buffer In C/C++
- scanf() and fscanf() in C - Simple Yet Poweful
- getchar_unlocked() - faster input in C/C++ for Competitive Programming
- endl vs \n in C++
- How to use getline() in C++ when there are blank lines in input?
- Operators in C | Set 1 (Arithmetic Operators)
- How to change the output of printf() in main() ?
- gets() is risky to use!