Can you not:
- split your string 'expression' into individual strings at the occurrences of '+'
- return this as a vector of strings
- 'stringstream' them (or use atof() or atoi()) into numbers
- add them up?
With a little care you could extend this to subtraction as well, but multiplication and division might run into precedence-of-operators issues.
One suggestion would be to:
- split your string 'expression' into individual strings at the occurrences of '+'
- return this as a vector of strings
- 'stringstream' them (or use atof() or atoi()) into numbers
- add them up
With a little care you could extend this to subtraction as well, but multiplication and division might run into precedence-of-operators issues.
#include <iostream>
#include <string>
#include <vector>
usingnamespace std;
// Function prototypes
vector<string> split( string s, constchar *delim );
string eraseChar( string s, char c );
//-------------------------------------
vector<string> split( string s, constchar *delim ) // Splits a string at anything in delim
{
vector<string> parts;
int i = 0, idelim;
s = eraseChar( s, ' ' ); // get rid of nuisance blanks
while( i < s.size() && i != string::npos )
{
idelim = s.find_first_of( delim, i + 1 ); // find start of NEXT item
if ( idelim == string::npos ) parts.push_back( s.substr( i ) );
else parts.push_back( s.substr( i, idelim - i ) );
i = idelim;
}
return parts;
}
//-------------------------------------
string eraseChar( string s, char c ) // Returns string without a particular character in
{
int i = 0;
string result = s;
while( i < result.size() )
{
if ( result[i] == c ) result.erase( i, 1 );
else i++;
}
return result;
}
You can then test this in full. Note that the following goes beyond your requirements because it allows minus as well as plus, as well as spaces anywhere in the expression.