-
Infinite Loop
In the earlier thread "Square Root Problem", I wrote a little program that contains this loop:
Code:
while (toupper(quit) != 'Y')
{
cout << "Please enter a non-zero number *****:" << flush;
cin >> userinput; //Get the number to be square rooted
if (userinput <= 0 | isascii (userinput)) //Is it a nonvalid number or letter?
{
cout << "The number you entered was invalid. Would you like to quit (y/n)?" << flush;
cin >> quit; //Does the user want to quit?
continue; //If he wants to quit, then quit. Else, continue.
}
a = userinput;
x = a;
/*********Square root loop*************/
lasty = 0; //Null out lasty
for (int i = 0; i <= 15; i++)
{
y = 0.5*(x+a/x); //This is our actual formula
x = y;
if (y == lasty)
{
break; //Our formula has reached its end prematurely (under 15 loops)
}
lasty = y;
}
If I enter a letter (but not an invalid number) I have an infinite loop. THis doesn't make sense as both invalid numbers and letters have the same processing after being detected. When I enter -1, it presents me with the correct prompt. However, the second I enter a letter, it goes into an infinite loop showing the correct prompt over and over again with no time to input anything. Any ideas?
-
-
>never mind, I fixed it.
Just a tip. When you solve your own problem, it's polite to describe how you solved it. This accomplishes two things:
1) If the solution is a good one, others can learn from it.
2) If the solution can be improved, others can offer advice for doing so and you can learn.
-
@Prelude:
Being an idiot, I didn't look at the FAQ. The solution is there. Here is the replacement code:
Code:
while (cout << "Please enter a non-zero number *****:" << flush && !(cin >> userinput))
{
cout << "The number you entered was invalid." << endl;
cin.clear();
cin.ignore(std::numeric_limits < int >::max(), '\n');
continue;
}
-
FWIW, note that the flush is unnecessary there as the use of cin causes an automatic flush. In addition, the continue is also unnecessary, the loop will automatically continue as it has reached the end of the block. That is why neither of those is part of the solution in the FAQ.
-
this was from a different thread, and I didn't write that code. It's just when I added an error checking statement for letters, it went into an infinite loop.
-
To be strictly correct, this code
Code:
cin.ignore(std::numeric_limits < int >::max(), '\n');
should be
Code:
cin.ignore(std::numeric_limits < std::streamsize >::max(), '\n');
http://cboard.cprogramming.com/showp...06&postcount=5
-
that has been copied straight from the FAQ, so maybe a revision?
-
Both are commonly used, and in practice both will work fine. If streamsize's max is smaller than int's max, then it is theoretically possible that some strange behavior could occur. The standard does specifically mention numeric_limits<streamsize>::max(), so that is probably the better one to use, but there's no need to rush and change it.