Hi, I just want to check if this line seem correct from RPN Calculator Line: if
ID: 3726535 • Letter: H
Question
Hi, I just want to check if this line seem correct from RPN Calculator
Line:
if ((input == "+" || input == "*" || input == "/" || input == "-") && mainStack.size() < 2)
{
}
Because if I delete that line, the program cannot output as the requeriment is expected to follow:
Code:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
#include "MyStack.h"
int main()
{
Stack<string> mainStack;
string input = "";
Stack<string> stackDup;
while (true)
{
if (mainStack.empty())
{
cout << "Enter: ";
}
else
{
string prompt = "Enter: ";
while (!stackDup.empty()) {
prompt += stackDup.peek() + " ";
stackDup.pop();
}
cout << prompt;
}
cin >> input;
if (input == "Q" || input == "q")
{
break;
}
if ((input == "+" || input == "*" || input == "/" || input == "-") && mainStack.size() < 2)
{
}
else {
if (mainStack.size() >= 2 && (input == "+" || input == "*" || input == "/" || input == "-")) {
double val1 = atof(mainStack.peek().c_str());
mainStack.pop();
double val2 = atof(mainStack.peek().c_str());
mainStack.pop();
double result = 0.0;
if (input == "+") {
result = val1 + val2;
}
else if (input == "*") {
result = val1 * val2;
}
else if (input == "-") {
result = val2 - val1;
}
else if (input == "/") {
result = val2 / val1;
}
ostringstream strs;
strs << result;
mainStack.push(strs.str());
}
else {
mainStack.push(input);
}
}
stackDup = mainStack;
}
}
Expected input:
Example: five plus six Enter: 5 [ENTER] Enter: 5 6 [ENTER] Enter: 6 5 + [ENTER] Enter: 11 Example: ten minus one Enter: 10 [ENTER] Enter: 10 1 [ENTER] Enter: 1 10 - [ENTER] Enter: 9 Q [ENTER] Example: one divided by two Enter: 1 [ENTER] Enter: 1 2 [ENTER] Enter: 2 1 / [ENTER] Enter: 0.5 Example: add with empty stack Enter: + [ENTER] Enter:
Example: Pi times the radius squared Enter: 3.14159 [ENTER] Enter: 3.14159 18 [ENTER] Enter: 18 3.14159 18 [ENTER] Enter: 18 18 3.14159 * [ENTER] Enter: 324 3.14159 * [ENTER] Enter: 1017.88 Example: (1+2)/(3+4) Enter: 1 [ENTER] Enter: 1 2 [ENTER] Enter: 2 1 + [ENTER] Enter: 3 3 [ENTER] Enter: 3 3 4 [ENTER] Enter: 4 3 3 + [ENTER] Enter: 7 3 / [ENTER] Enter: 0.428571 Example: add with one value in stack Enter: 1 [ENTER] Enter: 1 + [ENTER] Enter: 1
Explanation / Answer
Yes your line seems to be correct since in your expected output if there are less than to numbers then you do nothing if any operation comes and stack remains as it is.
You are checking this condition with your if statement which seems to be correct for this case.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.