DDT
DDT

Reputation: 33

Understanding "while (getchar() != '\n')"

I'd like to gain a little better understanding of how things work in the background in regards to this command.

I started off with trying to prevent my application from failing when scanf() received a char instead of the int it was expecting. The solution provided to me was to add the line while (getchar() != '\n'); to clear the input buffer. And it worked. Great!

But since I was otherwise using scanf() and not getchar() I found it a bit confusing that I use a completely different command for input to clear the buffer.

I have been Googling it a bit and from what I can tell, getchar() uses stdin and that is the buffer that is being cleared with that command. That would by extension also mean that scanf() is also using stdin in that case.

Is that assumption correct?

Upvotes: 3

Views: 2707

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Yes, that's the case. It is explicitly mentioned in the docs.

Quoting the C11 standard, chapter §7.21.6.2

The fscanf function reads input from the stream pointed to by stream, under control of the string pointed to by format that specifies the admissible input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. [....]

and chapter §7.21.6.4

The scanf function is equivalent to fscanf with the argument stdin interposed before the arguments to scanf.


Just to add a bit on why you need getchar() to clear the stdin when scanf() also reads from stdin:

scanf() only reads from the input buffer if the matching is success, pointed to by format that specifies the admissible input sequences. In case, the matching fails, which is your case, supplying char where int is expected (most likely, user use of %d conversion specifier), the input in the buffer remains unread and eligible to be read by next call to scanf().

Thus in case call to scanf() is made, it is always advised to check failure and clean up the buffer using getchar(), which reads the stdin, character by character and return the character read as an unsigned char cast to an int in every call, thereby consuming any entry in the buffer and clearing it.

Upvotes: 2

Blaze
Blaze

Reputation: 16876

I have been Googling it a bit and from what I can tell, 'getchar()' uses 'stdin' and that is the buffer that is being cleared with that command. That would by extension also mean that 'scanf' is also using 'stdin' in that case. Is that assumption correct?

Yes, that's correct.

According to the documentation (emphasis mine):

[scnaf] Reads data from stdin and stores them according to the parameter format into the locations pointed by the additional arguments.

Upvotes: 1

Related Questions