Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

invalid argument exception

Status
Not open for further replies.

deb9

Programmer
Joined
Sep 21, 2005
Messages
8
Location
US
Hi,

I have a method to read input from a user like this

int cmd = 0;
while (true) {
try {
cout << "Menu of options: 1) New game 2) Mark 3) Status 4) Exit";
cin >> cmd;
}
catch (?????) {
cout<<"Invalid input. Try again"<<endl;
continue;
}
}

I am using a try and catch block in case the user types a string or a non-numeric character. In that case I would like in the catch to just print the message and ask again.
What are the arguments to the catch? Do I need to include any exception library?

Thanks

Debbie

 
There is no exception thrown on invalid input, so the try/catch block is useless in this case.

To check for valid input, you check the return value of operator>>. If it is false, the input failed, and you need to clear the input stream fail state (and probably ignore the characters in the stream). Here is one way of doing this:
Code:
while (true) {
  cout << "Menu of options: 1) New game 2) Mark 3) Status 4) Exit";
  if (!(cin >> cmd)) {
    cout<<"Invalid input. Try again"<<endl;
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
    continue;
  }
  // ...
}
You must #include <limits> to use the numeric_limits there, or you can just replace that part with a large number like 100 or 1000 so that at most that many bad characters input by the user will be ignored.
 
I don't see any way that an exception can be thrown with that code. Here is the proper way to do what you want:
Code:
	int cmd = 0;
    while ( true )
	{
		cout << "Menu of options: 1) New game 2) Mark 3) Status 4) Exit";
		cin >> cmd;

		// Do something with cmd here...

		if ( !cin )			// If stream state is bad.
		{
			cin.clear();	// Set stream state back to good.
			cin.ignore();	// Ignore the bad input.
		}
		else if ( (cmd >= 1) && (cmd <= 4) )
		{
			continue;
		}

		cout << "Invalid input. Try again" << endl;
	}
 
Oops, I put the "// Do something..." in the wrong place.
Code:
    int cmd = 0;
    while ( true )
    {
        cout << "Menu of options: 1) New game 2) Mark 3) Status 4) Exit";
		
        if ( !(cin >> cmd) )	// If stream state is bad.
        {
            cin.clear();		// Set stream state back to good.
            cin.ignore();		// Ignore the bad input.
			cout << "Invalid input. Try again" << endl;
			continue;
		}
        else if ( (cmd < 1) || (cmd > 4) )
        {
			cout << "Invalid input. Try again" << endl;
			continue;
        }
		
        // Do something with cmd here...
    }
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top