-
infinite loop !
Hi, guys~
I just want to user input a number and then decide whether continue or not, but I met a infinite loop when testing it. my code is right below:
Code:
#include <iostream>
void main ()
{
int x;
while(1)
{
cout << "input a number: ";
cin >> x;
if (number==8)
{
break;
}
}
//if break then go to next step;
}
it works fine when input a simply number, but that mess comes when your input a string like "relrejlre" etc. How to calm it down ???
:confused:
-
look at the "atoi" (alpha to integer) function, an integer cannot handle input other than a number, and will crash, whereas if you use atoi ( stdio.h or stdlib.h i think ) it will convert to 0.
I think that is what you mean.
-
i ran nito the same problem as you. Good coding practice would be to put the loop in a try/catch block...but my program was for a buddy at work, so i left him an "easter egg" so to speak.
Code:
while (int theNumber<24&&int infiniteLoopCount<20)
{
std::cout<<"enter a number between 1 and 24"<<endl;
std::cin>>theNumber;
infiniteLoopCount++;
}
if (infiniteLoopCount<=10)
{
std::cout<<"Oh no! You've been caught in the INFINITE LOOP OF DEATH!!!\nNext time enter a number, have a nice day."<<endl;
//delete pointers and junk
exit(1);
}
now like i said, that's not exactly good coding practice, but the guy i made it for wasn't very computer savvy, and the look on his face was priceless :). But if it's a formal app just go with the try/catch block....if you really want you can model it after the above while loop, then use a goto command to repeat it.
-
Code:
#include <iostream.h>
int main(void)
{
int x;
while (1)
{
cout << "input a number: ";
cin >> x;
if (!cin.good())
{
cin.clear();
cin.ignore(10, '\n');
}
else if (x == 8) break;
}
}
-
This is better, IMHO:
Code:
#include <iostream.h>
int main(void)
{
int x;
while (1)
{
cout << "input a number: ";
cin >> x;
if (!cin.good())
{
//Clear all error flags
cin.clear();
//Remove all characters waiting to be read
while (cin.rdbuf()->in_avail() > 0) cin.get();
}
else if (x == 8) break;
}
}
-
Quote:
Originally posted by Hammer
Code:
#include <iostream.h>
int main(void)
{
int x;
while (1)
{
cout << "input a number: ";
cin >> x;
if (!cin.good())
{
cin.clear();
cin.ignore(10, '\n');
}
else if (x == 8) break;
}
}
thanx boys and girls~ :)
I just found cin.get and cin.ignore in my book, what about cin.good and cin.clear please £¿ :confused:
-
cin.good is what it says it is, if the input stream is good.
cin.clear does what it says, clears the input stream
-
it seems cin.clear and cin.good didnt works fine, what's the matter ? :confused: here is my code:
Code:
#include <iostream>
int i, j;
void main()
{
while(1)
{
cout << "please input a number: ";
cin >> i;
if (!cin.good())
{
cin.clear();
}
else
{
if(i==8)
{
cout << "good boy!";
break;
}
}
}
}