Tomwa ivory
Tomwa ivory

Reputation: 281

Flush input in C

I'm a student in software engineering and I'm on Christmas break in order to get better for the next semester I've been writing various console applications to practice. I have however ran into a problem, I need to get integer input from the user. I've been using fgets to get the string from stdin and then using sscanf to get the integer (Which has worked fine) but if the user enters more than my buffer size trailing characters are left in the stream (Including a newline with skips my next call to fgets). I've looked around and found that most people seem to suggest while(getchar() != '\n'); that however causes me a problem because if there isn't a newline character to be consumed an unnecessary scan for input takes place.

Example:

int ch;
char* buffer = (char*)malloc(BUFSIZ*sizeof(char));
while((ch = getchar()) != '\n' && ch != EOF);
fgets(buffer,BUFSIZ*sizeof(char),stdin);

If the buffer isn't too small and no trailing characters remain in the stream then there is an unecessary getchar() causing input.

Output:

A

A

You typed A

Intended Output:

A

You typed A

I hope that I made this clear enough, I appreciate any help.

Upvotes: 2

Views: 1356

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753675

Check whether the string you read includes a newline.

  • If there is a newline, you don't need to clear the input.
  • If there is no newline, read until you come across one.

On Unix, this loop is reasonable:

int c;
while ((c = getchar()) != EOF && c != '\n')
    ;

Note the EOF test compared with what you quoted (in the text of the question; this is what you quoted in your code snippet, but it is spread over two lines here, which is generally better for readability). I would do this 'gobbling' after the fgets(), rather than before the next one.

On Windows with the Microsoft compilers and libraries, you can play with fflush(stdin) if you are so minded. That has documented behaviour (see the MSDN web site). On Unix, trying fflush(stdin) yields undefined behaviour — don't do it.

Upvotes: 6

Related Questions