// FILE: calc.h
#include <iostream>
#include <stack> // Uses STL
#include <string> // Uses STL
using namespace std;
void evaluate_stack_tops(stack<double> & numbers, stack<char> & operations);
double read_and_evaluate(string line)
{
const char RIGHT_PARENTHESIS = ')';
stack<double> numbers; // local stack object
stack<char> operations; // local stack object
double number;
char symbol;
size_t position = 0;
while (position < line.length())
{
if (isdigit(line[position]))
{
number = line[position++] - '0'; // get value
numbers.push(number);
}
else if (strchr("+-*/", line[position]) != NULL)
{
symbol = line[position++];
operations.push(symbol);
}
else if (line[position] == RIGHT_PARENTHESIS)
{
position++;
evaluate_stack_tops(numbers, operations);
}
else
position++;
}
if (!operations.empty())
evaluate_stack_tops(numbers, operations);
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();
}
// FILE: Use_Stack.cpp
#include <iostream>
using namespace std;
#include "calc.h"
int main()
{
double answer;
string line;
cout << "Type a fully parenthesized arithmetic expression (SINGLE DIGITS ONLY!):\n";
getline(cin, line);
answer = read_and_evaluate(line);
cout << "That evaluates to " << answer << endl;
system("pause");
return 0;
}
一切正常,我可以输入简单的东西,如“2 4 3 * + 7 - 2 +”,但如果我想输入类似“123 60 +”的东西,那就不行了。我把它分成两个头文件。有人能给我一个如何接受多位整数的暗示吗?
答案 0 :(得分:0)
解决问题的一种方法是,您发现一个数字,而不是假设它只有一个数字长,使用循环来收集作为数字一部分的所有其他数字。当遇到非数字或空格时,循环将终止。
更好的方法是使用stringstream
标记输入字符串。在这种情况下,您可以将整行输入放入字符串中,然后使用类似于以下内容的while循环:
stringstream ss(line);
string token;
while (ss >> token) {
// do stuff with token
}
答案 1 :(得分:0)
RPN通过拥有一组您操作的值来工作。根据输入"13"
,从top=1
到top=13
的操作非常简单:top = 10 * top + digit