0

Does the input buffer gets cleared after scanf reads?

#include <stdio.h>

int main(void) 
{
    int a, b;
    scanf("%d", &a);//I inputted 3
    scanf("%d", &b);//I inputted 4
}

So when I gave the input 4 was 3 present in the input buffer?

  • Is your input `"4\n3\n"` or `"4 3\n"`? Also which mode is your tty in(raw, line, etc)? – user12986714 May 06 '20 at 17:17
  • The buffer is read and discarded up to the first character that stops the conversion, which remains in the buffer, along with anything after that. – Weather Vane May 06 '20 at 17:22
  • 1
    The answers below are a bit simplified. Your program and you typing into your console are asynchronous parallel processes. The OS keeps a queue of characters typed at the keyboard and programs consume them. The interface you are coding to is C streams. Until `scanf` returns with a status, it's impossible to say exactly what happened, without a debugging the entire system. – jwdonahue May 06 '20 at 17:22
  • Is this an [X/Y problem](https://en.wikipedia.org/wiki/XY_problem)? Are you trying to diagnose unexpected behavior of your program? – jwdonahue May 06 '20 at 17:25
  • @jwdonahue the question is simple as well (and very focused). I cannot guess if OP is asking it because it expects the first char to remain in the buffer or not.. – Roberto Caboni May 06 '20 at 17:26
  • @RobertoCaboni, well the OP seems to have found their answer. – jwdonahue May 06 '20 at 17:32
  • @jwdonahue so at least one answer (not mine :) ) wasn't too simplified. :) – Roberto Caboni May 06 '20 at 17:37

2 Answers2

1

So when I gave the input 4 was 3 present in the input buffer?

No, the 3 was consumed.

You cannot re-read it (as int or otherwise).

If you input "3<enter>" the 3 is consumed and the buffer contains just the "<enter>". You then type "4<enter>" which is added to the buffer. The 2nd scanf (*) consumes the initial enter and the 4 leaving "<enter>" for the next input operation.

(*) the conversion specifier "%d" skips optional leading whitespace and (tries to) converts the rest of the input to integer (if no errors occur).

pmg
  • 106,608
  • 13
  • 126
  • 198
0

So when I gave the input 4 was 3 present in the input buffer?

No, it wasn't.

scanf() reads (and consumes) from the standard input until a match the specified format (in your case an integer) is found. That format is converted and consumed as well.

Roberto Caboni
  • 7,252
  • 10
  • 25
  • 39