How do I flush the cin buffer?

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

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

13条回答
  •  不要未来只要你来
    2020-11-22 00:31

    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";
    

提交回复
热议问题