2013-12-17 37 views
0

我想在C++中做一個基本的數學標記器/解析器,它從控制檯獲取輸入然後標記它(最終進行解析)。然而,當我試圖5 * 5,我得到了一個有點問題:C++數學Tokenizer /解析器錯誤

我會得到打印到控制檯的53 -1 53所需的標記化的價值,但之後,我也得到了-1秒的無限量(它不停打印) 。問題是什麼?

main.cpp中

#include <iostream> 
#include <sstream> 
#include "tokenizer.h" 

int main(void){ 
    std::cout << "Please enter a mathematical expression" << std::endl; 
    std::string line; 
    std::getline(std::cin, line); 
    std::istringstream input(line); 
    tokenizer t; 
    std::vector<token> tokens(t.getTokens(&input)); 
} 

tokenizer.h

#include <vector> 
#include <sstream> 
#include "tokens.h" 

class tokenizer{ 
public: 
    std::vector<token> getTokens(std::istringstream* input); 
}; 

tokens.h

typedef const signed int token; 
enum tokens{ 
    mul = -1, 
    mDiv = -2, 
    add = -3, 
    sub = -4, 
    mPow = -5, 
    lparen = -6, 
    rparen = -7, 
    decpoint = -8 
}; 

tokenizer.cpp

#include "tokenizer.h" 
#include <iostream> 

token getToken(int tok); 

std::vector<token> tokenizer::getTokens(std::istringstream* input){ 
    std::vector<token> tokens; 
    while(input){ 
     int t = input->get(); 
     if(!isspace(t)){ 
      std::cout << getToken(t) << " "; // I added this line to see the values being added 
      tokens.push_back(getToken(t)); 
     } 
    } 
    return tokens; 
} 

token getToken(int tok){ 
    switch((char)tok){ 
    case '*': 
     return tokens::mul; 
    case '/': 
     return tokens::mDiv; 
    case '+': 
     return tokens::add; 
    case '-': 
     return tokens::sub; 
    case '^': 
     return tokens::mPow; 
    case '(': 
     return tokens::lparen; 
    case ')': 
     return tokens::rparen; 
    case '.': 
     return tokens::decpoint; 
    } 
    return tok; 
} 
+0

您是否檢查過INTO getToken的值?如果它的值爲-1,input-> get()返回-1是什麼意思? –

回答

2

整個輸入被讀取後,也只要它不是空的指針,std::istringstream將評估爲true。

+0

我應該刪除指針,還是使用'null_ptr'? – user2976089

+1

使用while(* input){...} –

+1

通過引用傳遞它,而不是指針。然後你的'while(輸入)'將評估輸入是否仍然好。 – Tim

1

tokenizer::getTokens()中的循環條件將始終在您的代碼中評估爲true。您可以嘗試將while(input)更改爲while(input->good())