ConsoleInput
From C
When standard input is a console (or terminal, or tty, or other standard keyboard-plus-display input-output device), the typical scenario is that it is line-buffered. This means that your program does not get any input until the user has typed and edited and entered a full line.
Standard input is an input stream. This means that characters placed into it will remain there until they are read by your program. "Flushing" an input stream does not make any sense. You cannot reliably read "all the characters which are in the stream". The stream includes all of the characters which have or will be entered and have not yet been read. If you want to ignore the rest of the line which was typed by the user, then simply read those characters:
int c; while ((c = getchar()) != EOF && c != '\n') continue;
If you want to read just one character, please note:
- You cannot read any character until the user types an entire line.
- You must read the rest of the line which was typed by the user before you can read more lines later.
You should read the line typed by the user. You should read the entire line, regardless of whether you need the entire line. If you do not read the entire line, you will still need to read the rest of the line before you can read the following line.
Reading long lines
Note that fgets()
has a fixed upper limit for the line length. There are several solutions to the long line problem listed in the Snippets article Snippets#reading_a_line_from_a_stream_without_artificial_limits. The solution given below handles long lines by not allowing them:
#include <stdio.h> #include <assert.h> static char * readline(char *line, size_t len) { line[len - 1] = '!'; return fgets(line, len, stdin); } static int linetoolong(const char *line, size_t len) { return line[len - 1] == '\0' && line[len - 2] != '\n'; } static char * prompt(const char *prompt, char *line, size_t len) { assert(len > 2); for (;;) { int good = 1; if (prompt) { fputs(prompt, stdout); fflush(stdout); } while ((line = readline(line, len)) && linetoolong(line, len)) good = 0; if (good || !line) break; fputs("Line too long\n", stderr); fflush(stderr); } return line; } #include <string.h> int main(void) { char line[100]; /* prompt user and read a line of user input */ while (prompt("Enter some stuff: ", line, sizeof line)) { /* strip trailing newline, if it exists */ line[strcspn(line, "\n")] = '\0'; /* do something with line */ printf(">>%s<<\n", line); } return 0; }