Jump to content
  • Advertisement


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

mark sandles

inputting numbers

This topic is 5452 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 been working on some simple maths games where the user must input numbers , but i have noticed if the user types a letter it messes the program up.
int main(void)
	cout << "Enter a number" << endl;

	int number = 0;

	cin >> number;
	cout << number << endl;

Do i have to read the numbers in as an array of chars then check each index for a letter to make the program not crash or is there an easier way? Thanks [edited by - Mark Sandles on August 14, 2003 12:11:28 PM] [edited by - Mark Sandles on August 14, 2003 12:12:16 PM]

Share this post

Link to post
Share on other sites
I had this problem as well. When you try to assign a char to an integer, cin seems to produce an error (which I think is odd, being as characters are represented as integers internally, and are even used interchangeably in many situations). To fix it, I do something like the following:

/* While the input isn''t valid... */
while (!(cin >> number))
/* Clear the error from the stream. */
/* Keep looping through the stream until a newline is reached. */
while (cin.get() != ''\n'')

Seems to work quite well. Used that in my Tic-Tac-Toe game I made this week.

Hope that helps,


Share this post

Link to post
Share on other sites
thanks hellz
that does the job nicely

Anyone have any further comments?
Like why it produces an error when you enter a char into an int .Why does it not store the chars asci code .

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.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!