If the user input a equation something like 2 + 2 * 2 + ( 2 - 2) infix expression.
how i collect the data to stack?
using string?
someone can give the algorithm.
I don't have idea to get the input.

## All 4 Replies

Visualize each number and each operator in the input string to be a token. Then, if each token is separated from the next by a space you can use >> to get each token into separate strings. If ()s are allowed, then typically they aren't separated from the numerical input by a space so you might have to account for that.

Once you have a tokenization protocol in place then one popular option would be to devise an infix/postfix conversion protocol and then use the reverse polish notation to do the actual calculations. To get more ideas you can search the board using keyphrases like RPN calculator, infix/postfix expressions, etc. to see prior discussions regarding these topics or you can go online and look up RPN calculator with your favorite search engine. You could even try working it out yourself and post questions you have along the way.

There are several ways you can convert the strings (tokens) representing numbers to numerical variable so you do the desired mathematical operations with them. They include stringstreams, sprintf(), functions similar to atoi() and subtracting '0' from each char representing a digit and then multiplying that by the appropriate power of 10 and adding the individual values together. As you can imagine some of these are prefered over others, but all of these are valid approaches.

Do a google search for "shunting yard algorithm".

But the problem is after i declared string token .
How i read the 1st number?
How i store the number?
I get the result is 49 when i push the item to the stack.
I think the string read the char only.

``````[LIST=1]
[*]#include <iostream>
[*]#include <stack>
[*]#include <string>
[*]using namespace std;

[*]int main()
[*]{
[*]	int i=0;
[*]	stack<double>operands;
[*]	stack<char>operators;
[*]	string token;
[*]	int a;

[*]	while(cin>>token)
[*]	{
[*]		if(isdigit(token[0]))
[*]		{
[*]			a=token[0];
[*]			operands.push(a);
[*]			cout<<operands.top();
[*]		}
[*]	}

[*]	return 0;
[*]}
[/LIST]``````

I'm not surprised. That program is woefully inadequate.

Have a look at the link below and `convert.cpp` . It should be enough to get you started.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.