How do I flush the cin buffer?

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

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

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

    The following should work:

    cin.flush();
    

    On some systems it's not available and then you can use:

    cin.ignore(INT_MAX);
    
    0 讨论(0)
  • 2020-11-22 00:26

    How about:

    cin.ignore(cin.rdbuf()->in_avail());
    
    0 讨论(0)
  • 2020-11-22 00:28
    cin.clear();
    fflush(stdin);
    

    This was the only thing that worked for me when reading from console. In every other case it would either read indefinitely due to lack of \n, or something would remain in the buffer.

    EDIT: I found out that the previous solution made things worse. THIS one however, works:

    cin.getline(temp, STRLEN);
    if (cin.fail()) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    
    0 讨论(0)
  • int i;
      cout << "Please enter an integer value: ";
    
      // cin >> i; leaves '\n' among possible other junk in the buffer. 
      // '\n' also happens to be the default delim character for getline() below.
      cin >> i; 
      if (cin.fail()) 
      {
        cout << "\ncin failed - substituting: i=1;\n\n";
        i = 1;
      }
      cin.clear(); cin.ignore(INT_MAX,'\n'); 
    
      cout << "The value you entered is: " << i << " and its double is " << i*2 << ".\n\n";
    
      string myString;
      cout << "What's your full name? (spaces inclded) \n";
      getline (cin, myString);
      cout << "\nHello '" << myString << "'.\n\n\n";
    
    0 讨论(0)
  • 2020-11-22 00:33

    Another possible (manual) solution is

    cin.clear();
    while (cin.get() != '\n') 
    {
        continue;
    }
    

    I cannot use fflush or cin.flush() with CLion so this came handy.

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

    Easiest way:

    cin.seekg(0,ios::end);
    cin.clear();
    

    It just positions the cin pointer at the end of the stdin stream and cin.clear() clears all error flags such as the EOF flag.

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