Advertisement
mvaganov

Safe number input using std::cin

Aug 24th, 2012
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.35 KB | None | 0 0
  1. int getNumber(char * prompt)
  2. {
  3.     int num;
  4.     do
  5.     {
  6.         if(std::cin.fail())
  7.         {
  8.             std::cin.clear();
  9.             //std::cin.ignore(1024, '\n'); // 1024 is arbitrary :-/
  10.             while(std::cin.get() != '\n'); // replaced above
  11.         }
  12.         if(std::cin.good())
  13.         {
  14.             std::cout << prompt << std::endl;
  15.             std::cin >> num;
  16.         }
  17.     }
  18.     while(std::cin.fail());
  19.     return num;
  20. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement