2016-02-12 106 views
1

我在C++中編寫了一個函數式函數。我的問題是否相當簡單。我正在閱讀一個文件「4 + 5」。所以我把它存儲成一個字符串。如何將字符串轉換爲數學公式

我的問題:

我該如何輸出9?因爲如果我只是cout < < myString ...輸出只是「4 + 5」

+0

如果你正在尋找一個快速的方法來做到這一點,我不認爲有一個。你幾乎必須從頭開始編寫它,這是大學級別的東西。 – immibis

+0

@immibis那麼,取決於你需要什麼。 '+,*,()'的遞歸下降解析器沒有花哨的錯誤處理,非常簡單。弗雷德溢出做了一個視頻,順便說一句。但就目前來看,這個問題當然太廣泛了。 –

+1

你的公式總是兩個數字的總和嗎? – d40a

回答

0

您可能需要做一些比您期望的更多的工作。您需要將每個操作數和運算符分別讀入字符串變量。接下來,一旦確認它們確實是整數,將數字字符串轉換爲整數。你可能會有一個角色裏面有操作數,你會做一些類似開關的情況來確定實際的操作數是什麼。從那裏開始,您需要根據變量中存儲的值執行開關箱中確定的操作並輸出最終值。

0

http://ideone.com/A0RMdu

#include <iostream> 
#include <sstream> 
#include <string> 

int main(int argc, char* argv[]) 
{ 
    std::string s = "4 + 5"; 
    std::istringstream iss; 
    iss.str(s); // fill iss with our string 

    int a, b; 
    iss >> a; // get the first number 
    iss.ignore(10,'+'); // ignore up to 10 chars OR till we get a + 
    iss >> b; // get next number 

    // Instead of the quick fix I did with the ignore 
    // you could >> char, and compare them till you get a +, - , *, etc. 
    // then you would stop and get the next number. 

    // if (!(iss >> b)) // you should always check if an error ocurred. 
      // error... string couldn't be converted to int... 

    std::cout << a << std::endl; 
    std::cout << b << std::endl; 
    std::cout << a + b << std::endl; 

    return 0; 
} 
0

你的輸出是 「4 + 5」,因爲 「4 + 5」 是像任何其他字符串例如: 「ABC」,而不是4和5是整數,+是操作員。 如果它涉及的不僅僅是添加2個數字,還可以將您的中綴表達式轉換爲使用堆棧表達和評估的後綴。

相關問題