2014-10-13 40 views
1
// 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

可能重複[?如何分析一個字符串,在C++中的int(http://stackoverflow.com/questions/194465/如何解析一個字符串到一個int-in-c) –

回答

0

解決此問題的一種方法是,您可以找到一個數字,而不是假定它只有一位數字,而是使用一個循環來收集數字中所有其他數字。循環會在遇到非數字或空格時終止。

更好的方法是使用stringstream來標記輸入字符串。在這種情況下,你會把輸入的整行成一個字符串,然後使用類似下面的while循環:由具有你操縱值的堆棧

stringstream ss(line); 
string token; 
while (ss >> token) { 
    // do stuff with token 
} 
+0

謝謝,我會試一試! – emanuel

0

RPN工作。給定輸入"13",從top=1top=13所需要的操作相當簡單:top = 10 * top + digit