why do I get an extra operator?

Hi I was trying to implement a reverse polish notation,and it works but...

here's the problem not all expressions are correctly parsed and they're duplicates

and I want to know why?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// ConsoleApplication2.cpp : main project file.

#include "stdafx.h"
#include <iostream>
#include <string>
#include <stack>

unsigned counter(std::string mark, unsigned pos)
{
	unsigned counter = 1;
	while (counter > 0)
	{
		if (mark[pos] == '(')counter++;
		else if (mark[pos] == ')')counter--;

		if (counter == 0)break;
		pos++;
	}
	return pos;

}

unsigned priority(char _operator)
{
	unsigned priority;

	switch (_operator)
	{
		case '+':
		case '-':
			priority = 1;
			break;
		case '*':
		case '/':
			priority = 2;
			break;
	}

	return priority;
}

bool _operator(char _operator)
{
	if (_operator == '+' || _operator == '-' || _operator == '*' || _operator == '/' )
		return true;
	else return false;
}

bool operand(char operand)
{
	if (operand >= '0' && operand <= '9') return true;
	else return false;
}

std::string parser(std::string infix)
{
	std::string parse = "";
	std::stack<char> stack;

	for (unsigned i = 0 ; i < infix.size(); i++)
	{
		if (operand(infix[i]))
		{
			while (operand(infix[i]))
			{
				parse += infix[i];
				i++;
			}
			i--;
			parse += " ";
		}
		else if (_operator(infix[i]))
		{
			if (stack.empty())
				stack.push(infix[i]);
			else if (priority(stack.top()) >= priority(infix[i]))
			{
				while (!stack.empty())
				{
					if (priority(stack.top()) >= priority(infix[i])) {
						parse += stack.top();
						stack.pop();
					}
					else break;
				}
				stack.push(infix[i]);
			}/*
			else
			{
				if (infix[i] != '(' || infix[i] != ')') {
					stack.push(infix[i]);
					parse += " ";
				}
			}*/

		}
		else if (infix[i] == '(')
		{
			unsigned j,k;
			j = counter(infix, i + 1);

			std::string sub = infix.substr(i + 1, j-1);
			parse += parser(sub);
			i = j;
		}
		
	}
	while (!stack.empty())
	{
		parse += stack.top();
		stack.pop();
	}
	return parse;
}


int main()
{
	std::cout << parser("5*((7-2)*(7+2)-5)")<<"\n";
}



the if for ( is when I have a nested expression so I can parse it as a seperate and add it to the current one that is being parsed.
Thank you for your time!
Last edited on
Nevermind I figured it out it's in the counter substr function.
I needed to substract from j i.
Topic archived. No new replies allowed.