Handling input errors, general question

This is a discussion on Handling input errors, general question within the C++ Programming forums, part of the General Programming Boards category; Hello, I'm trying to idiot-proof my program and I can't seem to figure out one part. I want to input ...

  1. #1
    Unregistered
    Guest

    Handling input errors, general question

    Hello,

    I'm trying to idiot-proof my program and I can't seem to figure out one part. I want to input integers for a menu system, but I get thrown into an infinite loop whenever somebody inputs a character or a string to the console. How can I stop this from happening?

    I've been trying to use cin.fail() but I can't get the stream to clear back out again. Is there a reliable way to handle a problem like this?

  2. #2
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    Either make a large while or do-while statement (depends on menu size)

    like

    do
    {
    cout << "Which choice?";
    cin >> My_int;
    }while ((My_int != 1)&&(My_int != 2));

    or

    provide a default value with an if statement if your integer requirement isn't met.
    Blue

  3. #3
    zen
    zen is offline
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    You could try this -

    Code:
    #include <iostream> 
    
    
    using namespace std;
    
    int main() 
    { 
    	int a;
    
    	cin>>a;
    
    	while(cin.fail())
    	{
    		cin.clear();
    		cin.ignore(80,'\n');
    		cin>>a;
    	}
    
    
    	return 0;
    }
    zen

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Checking array for string
    By Ayreon in forum C Programming
    Replies: 87
    Last Post: 03-09-2009, 03:25 PM
  2. Need some help with C program writing
    By The_PC_Gamer in forum C Programming
    Replies: 9
    Last Post: 02-12-2008, 08:12 PM
  3. User determined input question
    By lyoncourt in forum C Programming
    Replies: 8
    Last Post: 09-30-2007, 06:10 PM
  4. simple input and string manipulation question
    By Stig in forum C Programming
    Replies: 1
    Last Post: 12-15-2001, 12:33 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21