-
November 12th, 2003, 04:49 PM
#1
Getting a infinite loop when error checking
Why does this create a infinite loop if I enter a char?
//////////////////////////////////////////////////////////////////////
//CREATE ITEM
//////////////////////////////////////////////////////////////////////
void World::CreateItem()
{
int answer = 0;
do
{
cout << endl << "Item Level: ";
cin >> answer;
}while(!GoodChoice(0, answer, 50));
FirstItem->GenerateItem(this, answer);
}
//////////////////////////////////////////////////////////////////////
//GOOD CHOICE
//////////////////////////////////////////////////////////////////////
int World::GoodChoice(int lowest, int Num, int highest)
{
if ((Num <= lowest) || (Num > highest))
{
//A bad choice so print a message and return false
cout << endl << "I don't understand that choice." << endl;
return 0;
}
//Since we haven't returned, the choice is good
return 1;
}
-
November 12th, 2003, 04:55 PM
#2
What does your output look like?
-
November 12th, 2003, 05:18 PM
#3
I don't understand that choice.
Item Level:
I don't understand that choice.
Item Level:
I don't understand that choice.
Item Level:
Over and over and over, I need to ctrl c out of it to stop it
-
November 12th, 2003, 05:19 PM
#4
it works if I enter a number but it's when I enter a char like an 'a'
-
November 12th, 2003, 05:22 PM
#5
But you are asking for an integer. 'a' is not an integer, so answer gets the value 0, which is a bad choice according to your code. If you want a character, why aren't you asking for a character?
Correct is better than fast. Simple is better than complex. Clear is better than cute. Safe is better than insecure.
-- Sutter and Alexandrescu, C++ Coding Standards
Programs must be written for people to read, and only incidentally for machines to execute.
-- Harold Abelson and Gerald Jay Sussman
The cheapest, fastest and most reliable components of a computer system are those that aren't there.
-- Gordon Bell
-
November 12th, 2003, 05:29 PM
#6
thats why I have the error checking in place, if someone types something other than what I want I want it to display the message "I don't understand that choice." then go back to
Item Level: and wait for another entry.
-
November 12th, 2003, 05:29 PM
#7
When you enter an "a", the read fails, which sets the
failbit for the stream (cin in your case) AND does not
move the position in the stream (still points to the "a").
If an error occurs, you need to clear the state of the stream
and throw out the rest of the stream buffer :
Code:
cin >> answer;
if (cin.fail())
{
cin.clear();
cin.ignore(100,'\n');
}
-
November 12th, 2003, 05:33 PM
#8
Thanks a lot that did it..
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|