Results 1 to 6 of 6

Thread: Clearing cin buffer

Threaded View

  1. #1

    Thread Starter
    Hyperactive Member Comreak's Avatar
    Join Date
    Feb 2001
    Location
    Dis
    Posts
    319

    Clearing cin buffer

    I was tinkering with a recent program I made for my programming class which determines the difference between the ages of two people and I discovered a little bug: If the person enters something other than a numerical value, cin kinda wacks out. Here is the code I'm using to fix the problem:

    Code:
    int ErrorHandler()
    {
    		if(std::cin.fail())
    		{
    			std::cerr << "Input error \n";
    			std::cin.clear(); //Reset input failure indicators
    			
    			//Flushing buffer 
    			char BadInput[5];
    			std::cin >> BadInput;
    			return 0;
    		}
    		else
    		{
    			return 1;
    		}
    }
    It works, but if the user enters more than 4 characters, the program either ignores it or gives me an exception of some sort. Is there a better way to flush the buffer (I'm sort of a newb so I'm not to familiar with the methods for doing this yet)?
    Last edited by Comreak; Feb 20th, 2003 at 06:40 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width