How do I flush the cin buffer?

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

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

相关标签:
13条回答
  • 2020-11-22 00:15

    I have found two solutions to this.

    The first, and simplest, is to use std::getline() for example:

    std::getline(std::cin, yourString);
    

    ... that will discard the input stream when it gets to a new-line. Read more about this function here.

    Another option that directly discards the stream is this...

    #include <limits>
    // Possibly some other code here
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    

    Good luck!

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 00:17

    I would prefer the C++ size constraints over the C versions:

    // Ignore to the end of file
    cin.ignore(std::numeric_limits<std::streamsize>::max())
    
    // Ignore to the end of line
    cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n')
    
    0 讨论(0)
  • 2020-11-22 00:17

    cin.get() seems to flush it automatically oddly enough (probably not preferred though, since this is confusing and probably temperamental).

    0 讨论(0)
  • 2020-11-22 00:21

    Possibly:

    std::cin.ignore(INT_MAX);
    

    This would read in and ignore everything until EOF. (you can also supply a second argument which is the character to read until (ex: '\n' to ignore a single line).

    Also: You probably want to do a: std::cin.clear(); before this too to reset the stream state.

    0 讨论(0)
  • 2020-11-22 00:23
    #include <stdio_ext.h>
    

    and then use function

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