Patrick Sebastien
Patrick Sebastien

Reputation: 342

How do I check for nothing in the input buffer/stream in C?

I have searched for many solutions on this but none have met my needs.

I need to:

  1. Read two integers separated by spaces using scanf().
  2. If there is only one integer entered, I need to check for that and clear the buffer.
  3. If there are more than 2 integers entered, I need to check for that and clear the buffer.

So far I have been using getchar() to achieve the checking and clearing. The problem is that if there is nothing in the buffer, getchar() waits for a character.

How do I check to see if there is nothing in the input buffer/stream? This way if there is nothing, I don't have to clear the buffer with getchar().

Upvotes: 0

Views: 764

Answers (1)

chux
chux

Reputation: 154592

You can not do this with standard C - check for characters in the stdin buffer and immediately return if nothing exist.

Yet I do not think that is really needed here anyways. Just read a line using fgets(), waiting for the user to type 0 or more characters and then Enter which will put a '\n' in stdin. fgets() will then return.

Use "%n" to record where scanning was at that point and insure proper space delimiter and detect extra garbage.

char buf[100];
if (fgets(buf, sizeof buf, stdin) == NULL) Handle_EOF();
buf[strcspn(buf, "\n")] = '\0'; // lop off potential \n

int n1, n2;
int cnt = sscanf(buf, "%d%n%d%n", &d1, &n1, &d2, &n2);

if (buf[0] == '\0') Handle_NothingWasEntered();
else if (cnt == 1 && buf[n1] == '\0') Handle_OneWasEntered(d1);
else if (cnt == 2 && buf[n1] == ' ' && buf[n2] == '\0') Handle_TwoWereEntered(d1, d2);
else Handle_BadInput(buf);
}

Upvotes: 2

Related Questions