0

I have the following intention:

Take a string such as:

 string test = "2.0+2.5";

and convert this to the double 4.5. Is this possible? I also want to extend this to the complex type. I have more experience with Java but I am trying to work with C++. I attempted to use stringstream, however the double that I ended up with was only the 2. So I suppose it stops at the "+". Thanks for any help or pointers.

anon1001
  • 107
  • 6
  • 2
    You need an expression parser/evaluator. Now that you know the terminology, you can do a websearch. – David Heffernan Jun 03 '14 at 14:53
  • 5
    Please indicate what you have tried and what were your specific problems; if you have not tried yet, then it is not yet time for asking questions :) – Matthieu M. Jun 03 '14 at 14:53
  • David, thank you for the direction. Matthieu, see edited question. – anon1001 Jun 03 '14 at 14:57
  • `I have more experience with Java but I am trying to work with C++.` Expression evaluation has nothing to do with what language you've been using. You would have the same issue in Java as in C++ (and practically any other non-scripting language). – PaulMcKenzie Jun 03 '14 at 14:58
  • `I attempted to use stringstream, however the double that I ended up with was only the 2. So I suppose it stops at the "+". ` Before writing another line of code, you may be going down the wrong path in solving this problem. If your expressions get more complex, I'll tell you right now that there is no way you will "unpaint yourself" out of the corner you will be painting yourself in. There is a methodology to expression parsing, again, independent of the language you're using, and it isn't just going through the string as you're doing now. – PaulMcKenzie Jun 03 '14 at 15:01

1 Answers1

2

You can't eval strings in C++ as you can in scipted languages like Python etc. So you'd have to write code to parse the statement, something like:

double v1 = lexical_cast<double>( /* extract "2.0" from test */);
double v2 = lexical_cast<double>( /* extract "2.5" from test */);
double result = 0.0;
char op = // extract '+' from test
switch(op) {
case '+':
    result = v1 + v2;
    break;
// etc

alternatively, you could use a scripting language like Python from your C++ code to eval the statement as a string.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54