1

I was wondering if it would be possible to store caluclations contained in a string to integer. For example:

#include <iostream>
#include <string>
using namespace std;
int main()
{
string variable = "-123+432";
cout << stoi(variable) << endl;
}

This returns -123, would it be possible to make it return 309? Also what if there would be more calculations inside the string (eg. "-123+432*2"), and the person writing program would not know how many calculations will there be in a string (eg. string would be entered by user when the programm is runing).
Thanks for all answers

  • 1
    You are going to wat to read up on reverse polish notation and the shunting yard algorithm. That will help you build a parser that can tokenize the expression and allow you to evaluate it. – NathanOliver Nov 15 '21 at 17:33
  • The C++ standard library does not include runtime evaluation of mathematical expressions expressed in a string. You would need to find a library that can do this or write your own. – Drew Dormann Nov 15 '21 at 17:35

1 Answers1

1

It's possible for sure, but it's quite complicated to parse arbitrary strings, work out if they contain a valid mathematical expression and then work out the result.

Unless you are wanting to implement the solution yourself for fun, I would suggest looking up and using a 3rd party library that evaluates string expressions, for example https://github.com/cparse/cparse

This would allow you to do something like (probably not exactly correct, just for rough example):

int main()
{
string variable = "-123+432";
std::cout << calculator::calculate(variable, &vars) << std::endl;
}

If you are wanting to do this yourself for fun, I suggest you look up "Expression evaluation" and start from there. It's quite a large and complicated topic but a lot of fun to write your own evaluator imo.

Dharman
  • 30,962
  • 25
  • 85
  • 135
sji
  • 1,877
  • 1
  • 13
  • 28