/ Published in: C++
The bugged version: Somehow, it prints random characters to me like [] except the spaces filled in and other accented letters when I input more parenthesis and longer input.
How to use: example->
input:
3
1+2
(1+2)*(6-2)
6-7*(9*10)/8
output:
1 2 +
1 2 + 6 2 - *
6 7 - 9 10 ** 8 /
How to use: example->
input:
3
1+2
(1+2)*(6-2)
6-7*(9*10)/8
output:
1 2 +
1 2 + 6 2 - *
6 7 - 9 10 ** 8 /
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#include <iostream> #include <cctype> #include <string> #include <list> #include <stack> using namespace std; char pop(list<char> & a) //Pops the stack and returns it, I use it to append to output vector { char result = a.front(); a.pop_front(); return result; } int main() { int num; string in; cin >> num; string out; //stores outputed characters front operator stack list<char> opr; for(int zed=0; zed<num; zed++) { cin >> in; for(int i =0; i < in.length(); i++) { switch(in[i]) //Gets operator gets their precedence and pushes them into the stack(list) and //output string { case '(': opr.push_front(in[i]); break; case ')': while(opr.front()!='(' && !opr.empty()) { out.push_back(pop(opr)); } opr.pop_front(); break; case '-': if(opr.front() == '+' || '*' || '^' || '/' || '%') { out.push_back(pop(opr)); opr.push_front(in[i]); } else opr.push_front(in[i]); out.push_back(' '); break; case '+': if(opr.front() == '-' || '*' || '^' || '/' || '%') { out.push_back(pop(opr)); opr.push_front(in[i]); } else opr.push_front(in[i]); out.push_back(' '); break; case '*': if(opr.front() == '^' || '/' || '%') { out.push_back(pop(opr)); opr.push_front(in[i]); } else opr.push_front(in[i]); out.push_back(' '); break; case '^': opr.push_front(in[i]); out.push_back(' '); break; case '/': if(opr.front() == '^' || '*' || '%') { out.push_back(pop(opr)); opr.push_front(in[i]); } else opr.push_front(in[i]); out.push_back(' '); break; default: if(isdigit(in[i]) || isalpha(in[i])) //Default: if character is a digit or a letter append it to output out.push_back(in[i]); } } while(!opr.empty()) //if the stack isn't empty push the rest into the output vector { out.push_back(pop(opr)); opr.pop_front(); } out.erase(remove(out.begin(), out.end(),'('), out.end()); //remove those stupid parenthesis out.push_back('\n'); } cout << out; return 0; }