learningcode learningcode - 1 month ago 17
C# Question

Calculate numerical string expression value

I have a file like this, names input.txt

1+2
2+5
8*6
200/10


How can I calculate these and print them into an output.txt like below

1+2=3
2+5=7
8*6=48
200/10=20


Can someone suggest me how to do this?

Answer

You can do by DataTable like below-

add System.Data to your program. Suppose input.txt is your input file and output.txt is your output file then

DataTable dt = new DataTable();
List<string> lines = new List<string>();
var a = File.ReadAllLines("input.txt");

foreach (var s in a)
{
   lines.Add((s + "=" + dt.Compute(s, null)).Replace(" ", ""));       
}

File.WriteAllLines("output.txt", lines);
Comments