Is this the proper way to flush the C input stream?

前端 未结 4 1895
情深已故
情深已故 2020-12-07 04:03

Well I been doing a lot of searching on google and on here about how to flush the input stream properly. All I hear is mixed arguments about how fflush() is undefined for th

4条回答
  •  感情败类
    2020-12-07 04:27

    The problem is more subtile than it looks:

    • On systems with elaborate terminal devices, such as unix and OS/X, input from the terminal is buffered at 2 separate levels: the system terminal uses a buffer to handle line editing, from just correcting input with backspace to full line editing with cursor and control keys. This is called cooked mode. A full line of input is buffered in the system until the enter key is typed or the end-of-file key combination is entered.

    • The FILE functions perform their own buffering, which is line buffered by default for streams associated with a terminal. The buffer size in set to BUFSIZ by default and bytes are requested from the system when the buffered contents have been consumed. For most requests, a full line will be read from the system into the stream buffer, but in some cases such as when the buffer is full, only part of the line will have been read from the system when scanf() returns. This is why discarding the contents of the stream buffer might not always suffice.

    Flushing the input buffer may mean different things:

    • discarding extra input, including the newline character, that have been entered by the user in response to input requests such as getchar(), fgets() or scanf(). The need for flushing this input is especially obvious in the case of scanf() because most format lines will not cause the newline to be consumed.

    • discarding any pending input and waiting for the user to hit a key.

    You can implement a fluch function portably for the first case:

    int flush_stream(FILE *fp) {
        int c;
        while ((c = getc(fp)) != EOF && c != '\n')
            continue;
        return c;
    }
    

    And this is exactly what your clearInputBuf() function does for stdin.

    For the second case, there is no portable solution, and system specific methods are non trivial.

提交回复
热议问题