Archived

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

mark sandles

inputting numbers

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;

	return(0);
}
  
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. */
cin.clear();
/* Keep looping through the stream until a newline is reached. */
while (cin.get() != ''\n'')
continue;
}


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

Hope that helps,

--hellz

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