2

How to convert string "1+1" to sum (or minus, division, multiplication) in c++. I need to convert any string or text to mathematical operation.

Peter
  • 23
  • 5
  • 1
    Some of the answers to [this question](http://stackoverflow.com/q/11172217/3345375) might be helpful. – jkdev May 18 '16 at 00:31
  • 1
    duplicate: [Evaluating arithmetic expressions in C++](http://stackoverflow.com/questions/9329406/evaluating-arithmetic-expressions-in-c) – Eissa N. May 18 '16 at 00:40
  • 1
    If you want to evaluate the string at compile time: http://www.boost.org/doc/libs/develop/doc/html/metaparse/getting_started_with_boost_metap.html – Jerry Jeremiah May 18 '16 at 01:54
  • 2
    Possible duplicate of http://stackoverflow.com/questions/1933970/c-simple-operations-evaluation-class – Jerry Jeremiah May 18 '16 at 01:59
  • 1
    Another Boost answer (but at runtime this time): http://www.boost.org/doc/libs/1_41_0/libs/spirit/example/qi/calc2_ast.cpp – Jerry Jeremiah May 18 '16 at 02:00
  • Possible duplicate of [Converting String to Int in Java?](http://stackoverflow.com/questions/5585779/converting-string-to-int-in-java) – Evan Carslake May 18 '16 at 03:11

1 Answers1

1

You can use a for loop to extract the individual characters from the string and convert the numbers to int using stoi. Then you'd do something like a loop that looks at the first element in the int array and the first element in the symbol array and does the calculation on the first and second elements in the int array. Shouldn't be too hard. If you need any other assistance, I can probably help.

Edit: Just to make it a little more clear

Step 1: Separate numbers and characters from the string. Convert and store in separate arrays.

Step 2: Look at element 1 and 2 in int array.

Step 3: Look at symbol in char array.

Step 4: If statement or case that checks for symbol and performs operation on element 1 and 2 of int array.

user262163
  • 38
  • 6