2014-05-04 67 views
0

我試圖做一個循環y之後拿到的第一個數字= 但有時term1coffs的值爲:65( 有時值爲:?!65無支架如果輸入是:y = 1(x^3)+0.05(x^2)-2(x^1)-1如何從這個std :: string得到數字?

std::string fx = cwin.get_string("Enter a polynomial formula that has a form like this:  y=1(x^3)+2(x^2)+0.5(x^1)+1"); 

std::string j; 
//j is a condition to end for loop 

int n=2; 

std::string term1coffs; 
//to get the number before the bracket y= ?? (X^..... 

for (j=fx.substr(n,1);j=="(";n+0) 
{ 
n=n+1; 
} 

term1coffs=fx.substr(2,n); 
double term1coff= atof(term1coffs.c_str()); 
+4

不要做字符串解析,而是按照後綴轉換的邏輯,分開運算符和操作數。 – P0W

回答

1

傳統解析器做這樣的事情(用僞代碼):

do 
{ 
    get a character 
    if (character is operator) 
    { 
     store character as operator 
     convert operand to double 
     if conversion succeeded 
      store operand value 
     else 
      store operand as variable name 
     operand = ""; 
    } 
    else 
    { 
     add current character to operand 
    } 
} while(there is more to do) 

如果你想以後使用的分析結果進行計算,你可能要根據優先順序產生樹結構,考慮到括號這個基本原理是Shunting-Yard Algorithm

相關問題