Alternative to C library-function fflush(stdin)

后端 未结 2 957
半阙折子戏
半阙折子戏 2021-01-26 09:32

Can anyone explain how the following code could be explained, I dont understand it really.

while((c = getchar()) != \'\\n\' && c != EOF);
相关标签:
2条回答
  • 2021-01-26 10:06
    while((c = getchar()) != '\n' && c != EOF);
    

    This reads input characters until it reaches either the end of the line (i.e., getchar() returned '\n) or end-of-file or an error condition (i.e., getchar() returned EOF).

    If stdin is reading from the keyboard, it discards input until you press Enter.

    Leaving off the EOF check could give you an infinite loop if there's an input error, or if you trigger an end-of-file condition (on Unix, by typing Ctrl-D twice).

    This could be useful, for example, after using scanf() to read an integer. If you execute scanf("%d", &num); and type 123, it will read those 3 digits (and store the value 123 in n), but leave everything after that waiting to be read. The above line can be used to skip the rest of the input line.

    (An alternative, likely a better one, is to read whole lines using fgets() and parse them using sscanf().)

    This is not equivalent to fflush(stdin). A far as the C standard is concerned, calling fflush on an input stream has undefined behavior.

    Some implementations do define the behavior of fflush(stdin). On systems that use GNU libc, for example (most Linux system):

    For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.

    That's not the same as discarding input up to the end of the line. And using it makes your code non-portable.

    0 讨论(0)
  • 2021-01-26 10:19

    This code, assuming the file (or some other input) has been opened, will continue to get character by character until it finds a newline (\n) or an end of file (eof).

    fflush will just clear the stream for an open file.

    0 讨论(0)
提交回复
热议问题