Thread: cin.fail() function

  1. #1
    -
    Join Date
    Feb 2003
    Posts
    47

    cin.fail() function

    Ill throw my code at you first

    Code:
    int menu(int &answer)
    {
        do {
            cout << "----Menu----"  << endl
                 << "1 something"   << endl
                 << "2 something"   << endl
                 << "3 something"   << endl
                 << "Please select an option (1, 2, or 3): ";
            cin >> answer;
            
            if (( cin.fail() ) == 1) {
                    cin.clear();
                    cout << "Please enter a valid option" << endl;
            }
            else if ((answer != 1) && (answer != 2) && (answer != 3)) {
                    cout << "Please enter a valid option" << endl;
            
            }
        } while ( (answer != 1) && (answer != 2) && (answer != 3) );
        
    return answer;
    }
    now it seems to handle most error type inputs except if u enter a character and i thought cin.fail and what i have done might be able to deal with it but it doen't, Have i used the function wrong? And if so could i have some help in correcting it. thanks.

  2. #2
    Registered User
    Join Date
    Mar 2002
    Posts
    1,595
    It's messy, but you could try something like this:
    Code:
    bool Int = false;
    bool validInt = false;
     
    while(!Int && !validInt)
    {
    cin >> answer;
    if(cin.fail())
    {
    	 cin.clear();
    	 cin.ignore(10000, '\n');
    	 cout << "you didn't enter an integer" << endl;
    	 cout << "Please enter a valid option" << endl;
    }
    else if((answer < 1) || (answer > 3)) 
    {
    	cout << "the int must be 1, 2, or 3" << endl;
    	cout << "Please enter a valid option" << endl;
    } 
    else
    {
    	 Int = true;
    	 validInt = true;
    }	 
    }
    Last edited by elad; 04-26-2004 at 01:20 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  2. Seg Fault in Compare Function
    By tytelizgal in forum C Programming
    Replies: 1
    Last Post: 10-25-2008, 03:06 PM
  3. Another syntax error
    By caldeira in forum C Programming
    Replies: 31
    Last Post: 09-05-2008, 01:01 AM
  4. Including lib in a lib
    By bibiteinfo in forum C++ Programming
    Replies: 0
    Last Post: 02-07-2006, 02:28 PM
  5. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM