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
>Solution :
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.