Getting operator sign

I'm trying to create a program that will solve a math problem, I have to do it the long way.

How do I determine the operator sign?

So, if my input is:
AAB+BAB
ABA-BBB
BCA*AAB

How do I check if AAB+BAB has a + sign in it and has to perform the addition method?
Same thing for the - and *.
Doing it the long way, when you have the "AAB+BAB" in an std::string or a char array, you have to iterate through it until you find a '+', or 0.
You can have std::string::find do the loop for you.
So, how exactly do I do this?

I know using the string.find('+') will return the location of the +.
But I do I make it check which operator is in there.

AAB+BAB

+
Check for +, if not found, go to -
if found, return operator

-
Check for -, if not found, go to *
if found, return operator

*
Check for *, if not found, prompt incorrect problem error
if found return operator
Try this (not tested):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <regex>


std::string str = "1+2";
std::tr1::cmatch res;

std::tr1::regex rx("^([0-9]{1,})([\\+|-|/|\\*]{1})([0-9]{1,})$");
if ( false == std::tr1::regex_search(str.c_str(), res, rx) {
std::cout << "Invalid input !" << endl;
} else {
std::cout << res[1] << " " << res[2] << " " << res[3] << endl;
}

Last edited on
When you have the location of +, split the string at that point, evaluate each half and then use a sequence of ifs to perform the right operation. I'm not sure that kind of operations you can do with AAB and BAB though. You never said what the exact problem was.
Topic archived. No new replies allowed.