Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting calculation contained in string to integer – C++

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading