While Loop Question

A

AJ Smith

To Whom It May Concern:

I have the following code:

#include <cctype> //Provides isdigit
#include <cstdlib> //Provides EXIT_SUCCESS
#include <cstring> //Provides strchr
#include <iostream> //Provides cout,cin,peek,ignore
#include <stack> //Provides the stack template class

using namespace std;

double read_and_evaluate(istream& ins);

void evaluate_stack_tops(stack<double>& numbers,
stack<char>& operations);

int main()
{
double answer;

cout<<"Type a fully parenthesized arithmetic expression:"
<<endl;
answer = read_and_evaluate(cin);
cout<<"That evaluates to "<<answer <<endl;

return EXIT_SUCCESS;
}

double read_and_evaluate(istream& ins)

{
const char DECIMAL = '.';
const char RIGHT_PARENTHESIS = ')';

stack<double> numbers;
stack<char> operations;
double number;
char symbol;

while(ins && ins.peek() != '\n')
{
if(isdigit(ins.peek()) || (ins.peek() == DECIMAL))
{
ins >> number;
numbers.push(number);
}

else if(strchr("+-*/", ins.peek()) != NULL)
{
ins >> symbol;
operations.push(symbol);
}

else if(ins.peek() == RIGHT_PARENTHESIS)
{
ins.ignore();
evaluate_stack_tops(numbers, operations);
}

else
ins.ignore();
}

return numbers.top();
}

void evaluate_stack_tops(stack<double>& numbers,
stack<char>& operations)
{
double operand1, operand2;

operand2 = numbers.top();
numbers.pop();
operand1 = numbers.top();
numbers.pop();
switch(operations.top())
{
case '+': numbers.push(operand1 + operand2);
break;

case '-': numbers.push(operand1 - operand2);
break;

case '*': numbers.push(operand1 * operand2);
break;

case '/': numbers.push(operand1 / operand2);
break;
}

operations.pop();
}

I'm trying to add a while loop that will ask the user if they would
like to try again and allow or exit. Any suggestions on where to
input it and how?

Thanks....
 
D

Daniel T.

"AJ Smith said:
I'm trying to add a while loop that will ask the user if they would
like to try again and allow or exit. Any suggestions on where to
input it and how?

bool try_again() {
cout << "Try again? (y/n) ";
char choice;
cin >> choice;
return choice == 'y';
}

int main()
{

do {
double answer;

cout<<"Type a fully parenthesized arithmetic expression:"
<<endl;
answer = read_and_evaluate(cin);
cout<<"That evaluates to "<<answer <<endl;
} while ( try_again() );

return EXIT_SUCCESS;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,756
Messages
2,569,533
Members
45,007
Latest member
OrderFitnessKetoCapsules

Latest Threads

Top