How do I flush the cin buffer?

前端 未结 13 1076
無奈伤痛
無奈伤痛 2020-11-22 00:14

How do I clear the cin buffer in C++?

13条回答
  •  时光说笑
    2020-11-22 00:15

    I prefer:

    cin.clear();
    fflush(stdin);
    

    There's an example where cin.ignore just doesn't cut it, but I can't think of it at the moment. It was a while ago when I needed to use it (with Mingw).

    However, fflush(stdin) is undefined behavior according to the standard. fflush() is only meant for output streams. fflush(stdin) only seems to work as expected on Windows (with GCC and MS compilers at least) as an extension to the C standard.

    So, if you use it, your code isn't going to be portable.

    See Using fflush(stdin).

    Also, see http://ubuntuforums.org/showpost.php?s=9129c7bd6e5c8fd67eb332126b59b54c&p=452568&postcount=1 for an alternative.

提交回复
热议问题