Do-while loop error

Im writing a do-while loop for my calculator program, but it needs to quit right of the bat if the user enters Q. When i type Q why does it proceed to still ask for the 1st and 2nd number. The program also doesn't continue after typing the first 2 values, the program should continue until Q is written right?

#include <iostream>
#include <stdio.h>
#include <cmath>

using namespace std;

int main()
{
char op;
do{
double num1, num2, dResult; // input and fp result
int iResult = 0; // integer result
char op; // operation
bool error = false; // true if error


cout << "Select the operation (+, -, *, /, %, or Q to Quit): ";
cin >> op;

cout << "Enter the first number: ";
cin >> num1;

cout << "Enter the second number: ";
cin >> num2;

switch (op)
{

case '+':
dResult = num1 + num2;
break;

case '-':
dResult = num1 - num2;
break;

case '*':
dResult = num1 * num2;
break;

case '/':
if (num2 != 0)
dResult = num1 / num2;
else
{
error = true;
printf("Error: Can't divide by zero!\n");
}
break;

case '%':
iResult = static_cast<int>(num1) % static_cast<int>(num2);
break;
}


if (!error)
{
if (op == '%')
printf("The result is: %d\n", iResult);
else
{
if (abs(dResult) > 1)
printf("The result is: %f\n", dResult);
else
printf("The result is: %.3f\n", dResult);
}

return 0;
}
else
return -1; // error

} while(op != 'q' || op != 'Q');
}
Last edited on
Hello ChrisValvo,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button, but you may still need to add indenting.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.




When i type Q why does it proceed to still ask for the 1st and 2nd number.



Because you told it to. Look at your code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
do
{
	double num1, num2, dResult; // input and fp result
	int iResult = 0; // integer result
	char op; // operation
	bool error = false; // true if error


	cout << "Select the operation (+, -, *, /, %, or Q to Quit): ";
	cin >> op;

	cout << "Enter the first number: ";
	cin >> num1;

	cout << "Enter the second number: ";
	cin >> num2;

	switch (op)
        {

Line 9 gives a prompt. Line 10 is where you enter "Q". And where does it go from there?
Lines 12 and 13 then lines 15 and 16. Just like you told it to.

Now the "switch" has no"case" for "Q" you essentially bypass the switch and continue with the next line, the if statement.

What you could try is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
do
{
	double num1, num2, dResult; // input and fp result
	int iResult = 0; // integer result
	char op; // operation
	bool error = false; // true if error


	cout << "Select the operation (+, -, *, /, %, or Q to Quit): ";
	cin >> op;

        if (std::toupper(op) == 'Q')  //<--- Requires header file "<cctype>".
            continue;  // <--- Will go to end of loop and check condition.

	cout << "Enter the first number: ";
	cin >> num1;

	cout << "Enter the second number: ";
	cin >> num2;

	switch (op)
        {


Andy
I tried adding what you said and now when I type 'Q' the program continues looping the statement "Select the operation", the program should quit right? Or am I understanding loops wrong.
Also say I type '+', then typed 2 *enter then 2* enter again I get 4, the program should continue and not force exit, UNTIL the user enters 'q' or 'Q' right?
Hello ChrisValvo,

To your first. Yes I think.

And the second. Yes.

You really need to post the changes so I can see what you have changed.

The change I added should work. At least it did in VS2017. I have not had a chance to test it elsewhere yet.

Andy
My teacher said add a case for Q but I just don't understand what's wrong I removed what you typed bc when I entered it, it just looped the statement "Select the operation."

#include <iostream>
#include <stdio.h>
#include <cmath>

using namespace std;

int main()
{
bool done = false;

do{
double num1, num2, dResult; // input and fp result
int iResult = 0; // integer result
char op; // operation
bool error = false; // true if error


cout << "Select the operation (+, -, *, /, %, or Q to Quit): ";
cin >> op;

cout << "Enter the first number: ";
cin >> num1;

cout << "Enter the second number: ";
cin >> num2;

switch (op)
{

case '+':
dResult = num1 + num2;
break;

case '-':
dResult = num1 - num2;
break;

case '*':
dResult = num1 * num2;
break;

case '/':
if (num2 != 0)
dResult = num1 / num2;
else
{
error = true;
printf("Error: Can't divide by zero!\n");
}
break;

case '%':
iResult = static_cast<int>(num1) % static_cast<int>(num2);
break;

case 'q':
case 'Q':
done = true;
break;
default: "Closing Program";
}


if (!error)
{
if (op == '%')
printf("The result is: %d\n", iResult);
else
{
if (abs(dResult) > 1)
printf("The result is: %f\n", dResult);
else
printf("The result is: %.3f\n", dResult);
}

return 0;
}
else
return -1; // error

} while(!done);
}
I've watched countless tutorials on do-while loops but it just seem like my circumstance is different in this program unless I just don't understand it still, I could really use help and its very appreciated as well
do while is just a loop.
the only notable difference is that it executes the loop body one time no matter what.
that makes it great for user input:

string s;
do
cout << "\n Type anything, but if you type the word quit the program will end\n";
cin >> s;
while (s!= "quit");

that happens once, no matter what.
if you instead said
while(s!="quit") it would never execute the loop body if s were "quit" when it got to the while line.

everything else after that is pretty much a loop as usual … it does what it does and goes again until something makes it stop.

you use a do while when you catch yourself seeding the condition, then:
stop = false; //outside the loop, seeding to force it to loop one time.
while(!stop) …. //hey, that looks like it shoulda been a do-while because of the initial setup pre-loop.



Last edited on
I get what ur saying, I just don't know how to implement it in my program
Why is my program not repeating after I type the first set of calculations, it should keep going until 'Q' or 'q' is hit or my laptop dies
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
       if (!error)
        {
            if (op == '%')
                printf("The result is: %d\n", iResult);
            else
            {
                if (abs(dResult) > 1)
                    printf("The result is: %f\n", dResult);
                else
                    printf("The result is: %.3f\n", dResult);
            }

            return 0;
        }
        else
            return -1; // error

    } while (!done);  // not reached
}

If error is not set, you return 0. If error is set, you return 1.
You never each the end of your loop.

You have been asked to use code tags. PLEASE DO SO.
http://www.cplusplus.com/articles/jEywvCM9/
Hint: You can edit your post, highlight your code and press the <> formatting button.
If you're not going to make the slightest bit of effort to make your posts readable, why should we spend the slightest bit of effort helping you?

Hello ChrisValvo,


PLEASE ALWAYS USE CODE TAGS (the <> formatting button), to the right of this box, when posting code.

Along with the proper indenting it makes it easier to read your code and also easier to respond to your post.

http://www.cplusplus.com/articles/jEywvCM9/
http://www.cplusplus.com/articles/z13hAqkS/

Hint: You can edit your post, highlight your code and press the <> formatting button, but you may still to indent your code.

You can use the preview button at the bottom to see how it looks.

I found the second link to be the most help.

If you are not going to follow instructions people will not waste their time with your code.


Why is my program not repeating after I type the first set of calculations


Because you told it not to repeat.

After the switch you have this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
		if (!error)
		{
			if (op == '%')
				printf("The result is: %d\n", iResult);
			else
			{
				if (abs(dResult) > 1)
					printf("The result is: %f\n", dResult);
				else
					printf("The result is: %.3f\n", dResult);
			}

			return 0;
		}
		else
			return -1; // error

	} while (!done);  //  End of do/while loop.
}  //End of "main". 

Line 13 tells the program to end the program, so you never reach line 18 to finish the do/while loop.

I was also wondering if you could find a more dificult way of doing this part?

You seam to be going the wrong way to accomplish what should be very easy.

This does the same as what you started with, but in a different way. I tried to use as much of your original code as I could, so this could be done better, but you may have to rewrite the whole program.
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <cctype>  // <--- Added.
#include <iostream>
#include <iomanip>
#include <limits>  // <--- Added.
//#include <stdio.h>  // <--- If you are going to use what you do not nee than use "<cstdio>".
//#include <cmath>  // <--- Really do not need the "abs" function.

using namespace std;

int main()
{
	bool done = false;
	char op;

	std::cout << std::fixed << std::showpoint << std::setprecision(4);

	do
	{
		double num1{}, num2{}, dResult{}; // input and fp result
		int iResult = 0; // integer result
		//char op{}; // operation  // <--- Does not work with the while condition. And does not change "op" defined above the do/while loop.
		//bool error = false; // true if error.  Not needed.


		cout << "\n Select the operation (+, -, *, /, %, or Q to Quit): ";
		cin >> op;

		if (std::toupper(op) != 'Q')
		{
			cout << "\n Enter the first number: ";
			cin >> num1;

			cout << " Enter the second number: ";
			cin >> num2;
		}

		std::cout << '\n';

		switch (op)
		{
		case '+':
			dResult = num1 + num2;
			break;

		case '-':
			dResult = num1 - num2;
			break;

		case '*':
			dResult = num1 * num2;
			break;

		case '/':
			while (num2 == 0)
			{
				std::cerr << "\n    Error: Can't divide by zero!\n";  // <--- Use "std::cerr" not "printf".

				std::cout << "\n Please enter a number other than (0): ";
				std::cin >> num2;
			}

			dResult = num1 / num2;

			break;

		case '%':
			iResult = static_cast<int>(num1) % static_cast<int>(num2);
			break;

		case 'q':
		case 'Q':
			done = true;
			std::cout << "\nClosing Program\n";
			break;

		default:
			std::cout << "\n    Invalid operator\n";

		}  //  End switch.

		if (op == '%'  && !done)
			std::cout << "The result is: " << iResult << '\n';  // <--- Use "std::cout" not "printf".
		else if (!done)
			std::cout << "The result is: " << dResult << '\n';  // <--- Use "std::cout" not "printf".

	} while (std::toupper(op) != 'Q');

	// A fair C++ replacement for "system("pause")". Or a way to pause the program.
	// The next line may not be needed. If you have to press enter to see the prompt it is not needed.
	std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');  // <--- Requires header file <limits>.
	std::cout << "\n\n Press Enter to continue: ";
	std::cin.get();

	return 0;  // <--- Not required, but makes a good break point.
}

In the divide case you check for divide by (0) and deal with it there. I do not know if this is acceptable for your program or not. You can always change to an if statement, print the error message and set "done" to true to exit the do/while loop and end the program if needed.

Look it over and see what you think.

Andy
That makes a lot more sense and I guess it was the way I set up my program that made it more difficult, the comments you added helped me understand what I was doing wrong, I was only using print f bc my teacher said we HAD too and for some reason it didn’t make sense.
My teacher teaches us 1 subject at a time but since corona took over it’s been hard to study and ask questions, you seem very experienced, is there any helpful site you use to practice code. A lot of the time when I see a program being designed it contains stuff I’ve never seen before such as “toupper”. I want to be more familiar with these terms so my brain isn’t stuck in a box lol.
The only reason my code even looked the way it did originally was bc my teacher layed out a format saying the input, output and math cases HAD to be inside of the while case
Also thank you very much for the help, you saved me from headache this was causing lol.
Topic archived. No new replies allowed.