fflush() function not working with stdin

前端 未结 1 1797
栀梦
栀梦 2021-01-25 17:28

I\'m sorry for this silly question. I have C program to prompt user to enter age and name and then print the age and name to the screen. This is my exercise that I read from boo

1条回答
  •  隐瞒了意图╮
    2021-01-25 18:27

    fflush is meant to work with output or update streams and using it with an input stream is undefined behavior, from cppreference C section for fflush:

    The behavior is undefined if the given stream is of the input type or if the given stream is of the update type, but the last I/O operation was not an output operation.

    undefined behavior is behavior that the standard does not specify and it means that the result of your program is unpredictable, which could mean behavior that seems normal or a crash or other undesirable effects.

    cppreference is consistent with the language in the draft C99 standard section 7.19.5.2 The fflush function which says:

    If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

    Although this is not really your question and it seems like you have figured out a work-around, the question C, flushing stdin covers some proper ways of flushing stdin.

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