Jump to content
  • Advertisement


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

The Orange Peanut

Errorproofing user input

This topic is 5553 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!