Hey all! I'm new to C++ and am having trouble with the Do...While loop terminating. My problem is I want the loop to end when the user enters 'X' when asked for an operation. When 'X' is entered it still asks for a number and then displays the current total before ending. Is there any way to get the program to end immediately after the user enters 'X'? I understand I can use an If statement and break the loop when operation == 'X' but I feel like this would defeat the purpose of using a Do....While loop.

#include <iostream>

using namespace std;

int main() 
{
	double start = 0, number;
	char operation;

	cout << "Current total is " << start << endl;

	do
	{
		cout << "Enter an operation: + - * / (or enter X to exit):";
		cin >> operation;
		cout << "Enter a number: ";
		cin >> number;
		 if (operation == '+')
			start = start + number;
		else if (operation == '-')
			start = start - number;
		else if (operation == '*')
			start = start * number;
		else if ((operation == '/') && (number == 0))
			cout << "can not divide by zero!" << endl;
		else if (operation == '/')
			start = start / number;
		cout << "Current total is " << start << endl;
	} while (operation != 'X');

	
}
cin >> operation;
if(operation == 'X') break;

Input the operation before the do . Then just before the while input the next operation.

#include <cstdlib>
#include <iostream>

using namespace std;

int main()
{
double start = 0, number;
char operation;
startprog:
cout << "Current total is " << start << endl;
cout << "Enter an operation: + - * / (or enter X to exit):";
cin >> operation;
if (operation == 'X')
goto endprog;
cout << "Enter a number: ";
cin >> number;
switch(operation)
{
case '+':
   start = start + number;goto startprog;
   break;
case '-':
   start = start - number;goto startprog;
   break;
case '*':
   start = start * number;goto startprog;
   break;
case '/':
if ((operation == '/') && (number == 0))
   cout << "can not divide by zero!" << endl;goto startprog;
if (operation == '/')
   start = start / number;goto startprog;
   break;
}
endprog:
        return 0;
}

what do you think ?

what do you think ?

The code is terrible.
1) Doesn't use a loop
2) Uses the dreaded goto 3) Inconsistent indentation

You get a D, and only for the effort.
But you fail for trying to do someone else's homework for them. Here we help them solve their own problems, we don't solve them ourselves and let him cheat.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.