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

inputting numbers

This topic is 5235 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