This topic is now archived and is closed to further replies.

The Orange Peanut

Errorproofing user input

Recommended Posts

I have a cin statement that asks for an integer. Well, if a user input a string or something, the program just repeats the loop which the cin statement is in. It kind of looks like this
int MainMenu()
	int choice = 0;
	while((choice != 0) || (choice != 1) || (choice != 2) || (choice != 3))
		cout<<"\tSelect a play style."<<endl;
		cout<<"\t1 = Single Player"<<endl;
		cout<<"\t2 = Two Players"<<endl;
		cout<<"\t3 = Demo"<<endl;
	return choice;
Would now be a good time to learn how to use exceptions, or is there a better way to stop the program from crashing when a user puts invalid input? I guess I could use a switch statement, too, but that seems like a waste of a couple lines of code.

Share this post

Link to post
Share on other sites
If you want to prevent crashes, use getline();

Either getline with a limit, or getline with a std::string.

Then check the string for alpha characters, if it doesn''t have them, do a atoi() fuction to get your numbers.

yeah, that''s why people write code with buffer overflows, it''s because it''s easier just to let it crash.

"Go on then" - benjamin bunny.
Download and play Slime King I.

Share this post

Link to post
Share on other sites