PDA

View Full Version : Expression Evaluator in C++


amol0010
10-23-2009, 09:38 AM
Hi.

http://www.daniweb.com/code/snippet216831.html

The disclaimer is that I am not trying to pass the program as my own, just trying to think whether vectors were not used would there be a way to do it using regular strings ?

This is a link for an expression evaluator in C++.

I was wondering if this function:
void Equation::Next(string tmp)
{
vector <string> array;

int spaces = 0;
for ( int a = 0; a < tmp.length(); a++ )
{
if(tmp[a]==' ')
{
spaces++;
}
}
string token;
istringstream iss(tmp);
while ( getline(iss, token, ' ') )
{
array.push_back(token);
}

stack <string> my_stack;//initialise stack
vector <string> temp;
string ch;

for (int i = 0; i < spaces; i++)
{
string s;
s = array[i]; //make it easier to read

if ((s!="+")&&(s!="*")&&(s!="-")&&(s!="^")&&(s!="/"))
{
my_stack.push(s);
//push numbers onto the stack
}
else //i.e if it encounters an operator
{
my_stack.push(s);//push operator onto stack

for ( int i = 0; i < 3; i++ )
{
temp.push_back(my_stack.top());
my_stack.pop(); //erase from the stack
}

double z;
z = Eval(temp);
ostringstream outs;
outs << z; // Convert value into a string.
ch = outs.str();

my_stack.push(ch);
temp.clear();
}
}
cout << ch;

}




Is there a way to avoid using vectors in this function ?

push_back function is used on the vector here.


vector <string> array;

string token;
istringstream iss(tmp);
while ( getline(iss, token, ' ') )
{
array.push_back(token);
}


string array;

string token;
istringstream iss(tmp);
while ( getline(iss, token, ' ') )
{
array.push_back( (char) token);
}

I tried this code but it didn't work. Is this the right thing to do ? I am typecasting "token" as string here.

This is the error that shows up.

264 `struct std::string' used where a `char' was expected

What is going on here ?

amol0010
10-23-2009, 10:16 PM
Anyone ?

oracleguy
10-23-2009, 10:28 PM
Are you familiar with what data structure a vector is? You can't simply replace it with a string.

Also, you can't type cast a string which is an object to a base data type like that. If you want the character array behind the string, the string class has a c_str() method that returns it.

Oh and please be aware of our bumping rules:
Do not bump your thread repeatedly when you don't get a response. Sometimes when you post for help, you may not get a response in a timely matter, if at all. Forums aren't wishing wells, and some questions will fall through the cracks. That's a fact of life. It's ok to occasionally bump a thread, but only when done after an ample amount of time (ie: 2-3 days) have passed without a response, and never more than once, . Your thread is no more important than another member's when it comes to the amount of attention it should receive.