Trying to work this example out of my textbook and don't understand why it functions correctly with inputs of a=3 b=7 but not with a=0 b=3. Am I missing something? It seems to compile and run properly with whatever input I throw at it. Maybe just a glitch in the e-book? I'm using a chegg copy of Big C++ Late Objects 3rd edition.
#include <iostream>
usingnamespace std;
int main()
{
int a, b;
// Keep prompting the user until the input is correct
do {
cout << "Enter two positive integers, the first smaller than the second."
<< endl;
cout << "First: " << endl;
cin >> a;
cout << "Second: " << endl;
cin >> b;
}
while(a > b);
// Only print this when the input is correct
cout << "You entered " << a << " and " << b << endl;
}
So... just change the conditions required to stop the loop, like this?
while (a > b || a == b);
EDIT: Tried it that way in the Chegg textbook. No change. Part of the problem is that it doesn't give you the initial inputs unless the code executes properly.
That's a bit verbose (you could use a >= b instead), but yes. My main point was that code generally seems to work as desired (including the case where a == 0, b == 3
I'm not sure then. Maybe you could try putting return 0; at the end of your code. I've had strange behavior when working with automatic graders which provide the input.
#include <iostream>
usingnamespace std;
int main()
{
int a, b;
// Keep prompting the user until the input is correct
do
{
cout << "\n Enter two positive integers, the first smaller than the second.\n"
<< endl;
cout << " First: ";
cin >> a;
cout << " Second: ";
cin >> b;
} while (a > b); // <--- Back to the top of the loop to enter numbers correctly. [a < b or a == b] will cause the condition to fail.
// Only print this when the input is correct. Which is when a < b or a == b.
cout << "\n You entered " << a << " and " << b << endl;
return 0; // <--- Not required, but makes a good break point.
}