Link to home
Start Free TrialLog in
Avatar of techques
techques

asked on

How to convert a string formula into an int?

Hi

Here is the C# code:

string F = "((-5-9)+(9--5))";
Convert.ToInt32(F);

It throws invalid format exception.

How should I write it properly in VC#?
      
Avatar of David Robitaille
David Robitaille
Flag of Canada image

here a quick and dirty solution :
http://www.odetocode.com/Code/80.aspx
Avatar of techques
techques

ASKER

I do not run it in batch and so I changed the code.

Evaluator.EvalToInteger(F);

It throws nullpointer exception when executing object EvalToObject

Should I import any dll or library?

It is Dot net framework 2.0
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Text;
 
public class Evaluator
    {
        public static int EvalToInteger(string statement)
        {
            string s = EvalToString(statement);
            return int.Parse(s.ToString());
        }
 
        public static double EvalToDouble(string statement)
        {
            string s = EvalToString(statement);
            return double.Parse(s);
        }
 
        public static string EvalToString(string statement)
        {
            object o = EvalToObject(statement);
            return o.ToString();
        }
 
        public static object EvalToObject(string statement)
        {
            return _evaluatorType.InvokeMember(
                        "Eval",
                        BindingFlags.InvokeMethod,
                        null,
                        _evaluator,
                        new object[] { statement }
                     );
        }
 
        private static object _evaluator = null;
        private static Type _evaluatorType = null;
}

Open in new window

The point is to use Jscript`s eval function. so you you need "using Microsoft.JScript"
also, did you fully read the explanations at the top of the page????
"solution is to add a JScript.NET project to your solution"
"To compile, make sure you add a reference to the Microsoft.JScript assembly"



I use VS2005 and there is only J# project, but no JScript.NET project.

I added  Microsoft.JScript dll and using it. But, still nullreferenceexception

Is there any other way to do purely in VC#?

SOLUTION
Avatar of David Robitaille
David Robitaille
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Yes, it works in C#.

Thanks for help