开发者

C# Winforms - allow expressions in a textbox and return result

I'm trying to allow a user to either input a single numerical 开发者_如何学Cinput or multiple expressions into a textbox and have my application calculate the output. I'm sure this is a relatively easy problem but I've only been tackling C# for a short while - so bear with me.

To explain better, in a single textbox a user could either enter 4 or 1+1+1+1, in both instances the output would be 4.

I'm using both Visual Studio and Winforms.


You can use expression evaluator like this http://flee.codeplex.com/


string[] split = Textbox1.Text.Replace(" ","").Split(Convert.ToChar("+"));

double total = 0;
foreach (string str in split)
{
    double tempInt = 0;
    if (double.TryParse(str, out tempInt))
       total += tempInt;
}


System.Diagnostics.Debug.Write(total);


At a high level, it will simply be making a parser for your input and then handling it. So in your situation, you'd probably want to split on operators in the order of precendence, and then construct a tree of operations based on the input you receive. Then, parse the tree from the depth most nodes first on up.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜