Nov 27, 2019 at 8:11am Nov 27, 2019 at 8:11am UTC
In what way does the loop not work?
This loop here is nonsensical. If quit2 is false, it loops FOREVER. If quit2 is true, it doesn't even loop once. Why does this loop exist?
1 2 3 4 5 6
while (!quit2){
cout << "Check another number (Y/N)? " ;
cin >> checkAnotherNum;
cout << " " << endl;
}
Look at the code you posted. Look at line 41. Look at that
}
all the way over on the left. Doesn't that look odd?
Last edited on Nov 27, 2019 at 8:14am Nov 27, 2019 at 8:14am UTC
Nov 27, 2019 at 9:35am Nov 27, 2019 at 9:35am UTC
hmmmm (so NEW at this) But... should I delete that loop for it to work?
Nov 27, 2019 at 11:19am Nov 27, 2019 at 11:19am UTC
You should get it working without any loops to start with.
Mkae it take one input number, and tell you the right answer, and then finish.
When you've done that, you're ready to make it loop.
Nov 27, 2019 at 12:11pm Nov 27, 2019 at 12:11pm UTC
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 27 28 29 30 31 32 33 34 35
#include <iostream>
using namespace std;
float num;
string checkNumber;
string checkAnotherNum;
int main()
{
cout << " Check whether a number is positive, negative or zero: " << endl;
cout << " --------------------------------------------------------- " << endl;
cout << " Input a number: " << endl;
cout << " " << endl;
while (true ) {
cin >> num;
if (num > 0) cout << "The entered number is positive." << endl;
else if (num < 0) cout << "The entered number is negative." << endl;
else cout << "The entered number is zero." << endl;
my_label:
cout << "Check another number (Y/N)? " ;
cin >> checkAnotherNum;
if (checkAnotherNum == "Y" || checkAnotherNum == "y" )
continue ;
if (checkAnotherNum == "N" || checkAnotherNum == "n" )
return 0; // quits main()
cout << "Please enter only (Y/N): " << endl;
goto my_label;
}
}
It's sometimes difficult breaking through nested loops and tracking its conditions. Although some programmers decrying the use of 'goto', in some situations it helps to make the code much clearer.
Last edited on Nov 27, 2019 at 12:11pm Nov 27, 2019 at 12:11pm UTC