C # mathematical Operation expression Interpreter
Test file Contents:
a=2+3*2;b=2* (2+3);
Browse button Event handlers:
private void Button_browse_click (object sender, EventArgs e)
{
OpenFileDialog FBD = new OpenFileDialog ();
Fbd. Title = "Please select a file:";
Fbd. Checkfileexists = true;
Fbd. Checkpathexists = true;
Fbd. Filter = "*.txt (text file) |*.txt|*.* (all files) |*.*";
Fbd. FileName = Environment.getfolderpath (Environment.SpecialFolder.MyComputer);
if (FBD. ShowDialog () = = System.Windows.Forms.DialogResult.OK)
{
Textbox_savedir.text = FBD. FileName;
Try
{
FileStream fs = new FileStream (FBD. FileName, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader (FS);
while (!SR. Endofstream)
{
String line = Sr. ReadLine ();
Analyse (line);
}
}
catch (Exception ex)
{
MessageBox.Show ("error:" + ex.) Message + "\ r \ n Stack:" + ex. StackTrace);
}
}
}
Parse a row of expressions:
private void analyse (string line) { //with a semicolon as a terminator, support for writing multiple statements in one row string[] ExpA = lines. Split (new string[] {";"}, stringsplitoptions.removeemptyentries); for (int i = 0; i < expa.length; i++) { analyseexpa (expa[i]); } }
To evaluate an expression:
private void Analyseexpa (string ExpA) {string[] EXPB = exp A.split (new string[] {"="}, stringsplitoptions.removeemptyentries); for (int i = 0; i < expb.length; i++) {regex reg = new Regex ("[a-za-z]"); if (!reg. IsMatch (Expb[i])) {Object obj = evalexpress (expb[i]); if (obj! = null) {TextBox1.Text + = ExpA + "=" + obj. ToString () + "\ r \ n"; } else {TextBox1.Text + = ExpA + ", unrecognized expression \ r \ n"; } } } }