// 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 +」它不會工作。我把它分成兩個頭文件。有人可以給我一個關於如何接受多位數整數的提示嗎?如何在逆波蘭計算器中添加多位整數
可能重複[?如何分析一個字符串,在C++中的int(http://stackoverflow.com/questions/194465/如何解析一個字符串到一個int-in-c) –