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 121 122
|
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
using namespace std;
const int maxstack = 50;
const char initstack = ' ';
void createstack(char stack[], int& top)
{
int i;
top = -1;
for (i = 0; i < maxstack; i++) stack[i] = initstack;
}
bool emptystack(int top)
{
return top < 0;
}
bool fullstack(int top)
{
return top >= maxstack - 1;
}
void push(char stack[], int& top, char data)
{
if (!fullstack(top))
{
top++;
stack[top] = data;
}
else
cout << "The stack is full! Can't push value\n";
}
char pop(char stack[], int& top)
{
char ans = initstack;
if (!emptystack(top))
{
ans = stack[top];
stack[top] = initstack;
top--;
}
return ans;
}
int priority(char ch)
{
switch (ch)
{
case '+':
case '-':
return 1;
break;
case '*':
case '/':
return 2;
break;
default: cout << "Invalid Operator" << endl; // Outputs 9 times, not sure why
}
return 0;
}
void readem(char stack[], int& top)
{
int i, len;
string instring, outstring;
char ch;
ifstream inf;
ofstream outf;
inf.open("prog3.dat");
outf.open("prog3.ot");
while (!inf.eof())
{
inf >> instring;
outstring.clear();
len = instring.length();
for (i = 0; i < len; i++)
{
ch = instring[i];
if (ch >= 'A' && ch <= 'Z')
{
outstring += ch;
}
else
{
if (emptystack(top)) push(stack, top, ch);
else if (ch == '(') push(stack, top, ch); // Having trouble dealing with parentheses in output
else if (ch == ')')
{
while (!emptystack(top) && stack[top] != '(')
{
outstring += stack[top];
pop(stack, top);
}
}
else if (priority(ch) > priority(stack[top])) push(stack, top, ch);
else
{
while (!emptystack(top) && priority(ch) <= priority(stack[top])) outstring += pop(stack, top);
push(stack, top, ch);
}
}
}
while (!emptystack(top)) outstring += pop(stack, top);
outf << instring << " " << outstring << endl;
}
}
void main()
{
char stack[maxstack];
int top;
createstack(stack, top);
readem(stack, top);
}
|