inputting numbers

Started by
1 comment, last by mark sandles 20 years, 8 months ago
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]
Advertisement
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
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 .

This topic is closed to new replies.

Advertisement