Advertisement
BenTibnam

Clearing Input Buffer in C++

Apr 29th, 2020
814
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.74 KB | None | 0 0
  1. // example of filling the input buffer, clearing it to the end of the line so the user
  2. // can't miss entering the string due to the left over enter in the first use of cin
  3.  
  4. #include<iostream>
  5. #include<limits>
  6.  
  7. int main(int argc, const char* argv[]){
  8.     // filling the buffer with data
  9.     int x;
  10.     std::cin >> x;
  11.    
  12.     // clearing the buffer and warning flags to the end of the line
  13.     std::cin.clear();
  14.     std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  15.    
  16.     // filling buffer with string data
  17.     std::string s;
  18.     getline(std::cin, s);
  19.    
  20.     // clearing the buffer to the end of the file
  21.     std::cin.clear();
  22.     std::cin.ignore(std::numeric_limits<std::streamsize>::max());
  23.    
  24.     return 0;
  25. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement