Oct 30, 2017 at 11:51pm UTC
First of all, you should declare a bool variable as true.
Second, after your else statement, you should set that variable to false.
That should stop the loop.
Oct 30, 2017 at 11:57pm UTC
Yea take your code and run through it on a piece of paper pretend you're the computer! :) it will explain everything.
Basically
if (x<=0 || cin.fail()) == true
then
will always be true and youll just see
Invalid Input
Invalid Input
...
Last edited on Oct 31, 2017 at 12:06am UTC
Oct 30, 2017 at 11:59pm UTC
Thanks it works fine now. Hower, it doesn't ask the input again after an invalid input (as it did before). Any solutions?
Oct 31, 2017 at 12:02am UTC
Basically, you never asked it to ask for more input after your invalid input. It simply just breaks off after that. Assuming your code looks something like this
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
#include <iostream>
using namespace std;
int main()
{
int x;
bool goodInput = true ;
do
{
cout<<"Input cathetuses' length'" <<endl;
cin>>x;
if (x<=0 || cin.fail()){
cout<<"Invalid input" <<endl;
cin.clear();
goodInput = false ;
}else {
goodInput = true ;
}
}
while (goodInput);
return 0;
}
Last edited on Oct 31, 2017 at 12:11am UTC
Oct 31, 2017 at 1:13am UTC
Search do while loops and youll know why, do is only being ran once basically
Oct 31, 2017 at 1:19am UTC
But as i said before with negative numbers it works perfectly... I'm kinda confused.
Oct 31, 2017 at 1:20am UTC
So if you set the check to true, and say while (check), that will keep the loop going while the input is an int. However, it does not work if the input is a char. So I think something's wrong with the cin.fail and cin.clear.
Oct 31, 2017 at 1:25am UTC
Yeah i tried fixing it with cin.ignore() (which kinda fixes the problem), but other glitches came out.
Oct 31, 2017 at 1:41am UTC
Last edited on Oct 31, 2017 at 1:42am UTC
Oct 31, 2017 at 7:37am UTC
Just a lot of compile errors with:
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n' );
Last edited on Oct 31, 2017 at 7:37am UTC
Oct 31, 2017 at 7:42am UTC
Ok i included the library "limits". Everything works fine now. Thanks for the help.