-1

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?

Mostafiz
  • 7,243
  • 3
  • 28
  • 42
GreatDay
  • 55
  • 1
  • 9
  • 3
    Show the code that you tried. – AT-2017 Oct 13 '16 at 05:36
  • 1
    You will get an idea from this [Thread](http://stackoverflow.com/questions/234217/is-it-possible-to-compile-and-execute-new-code-at-runtime-in-net), Iterate through each line in the file evaluate them collect result to another file. **Try this and comeback with code if you face any difficulties** – sujith karivelil Oct 13 '16 at 05:41
  • 1
    Loop through each line of text and throw every line into an Integer. Hints: File.ReadLines and For Each – Fusseldieb Oct 13 '16 at 05:41
  • I've just had some codes to read the file, using filestream and streamreader. But I don't know how to split int and string and do some calculation with the ints (new to C#, sorry) – GreatDay Oct 13 '16 at 05:44
  • Thanks, I'll try and show some results later – GreatDay Oct 13 '16 at 05:45
  • See this. It may help - http://stackoverflow.com/questions/32166227/calculate-average-from-a-textfile-c-sharp In stackoverflow.com, you need to show what you have tried and stuck anywhere, then everyone is here to help. Good luck! – AT-2017 Oct 13 '16 at 05:46
  • @Fusseldieb you mean, the "+" can be an int? Sorry, I don't know that – GreatDay Oct 13 '16 at 05:46
  • @learningcode I just confirmed here, it doesn't work. Sorry... – Fusseldieb Oct 13 '16 at 05:51
  • @learningcode But, look: http://stackoverflow.com/questions/333737/evaluating-string-342-yield-int-18 – Fusseldieb Oct 13 '16 at 05:52

1 Answers1

1

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);
Mostafiz
  • 7,243
  • 3
  • 28
  • 42