I have set of lines which I read from a file that gets stored as an array stack of characters. A function called procssline gets called with the stored stack as a parameter. One of the lines reads as follows:
Nn<-<-<-<-No <-w iz<-sthe<-<-<- the time.
Where the top of the stack is the '.', and the bottom is the 'N' respectively.
The function processes the line by taking each "<-" as a 'backspace' and subsequently rewriting (pushing) the line into a result stack so that it would turn into this when I pop off the result stack and output the characters:
Now is the time.
I have access to the typical stack functions: pop, push, and peek. I'm trying to come up with an algorithm for it but I'm having difficulty coming up with a proper loop. This is my current version, which compiles, but doesn't run through properly and outputs the first character of the result of the first line as a '<'
void processLine(stack<char> &array, int linelength)
{
char catchvar1;
char catchvar2;
int bscount = 0;
stack<char> result;
for (int i = 0; i < linelength; i++)
{
array.pop(catchvar1); //pops first character
if (catchvar1 == '-') //if its a '-', then pop off the next character too
{
array.pop(catchvar2);
if (catchvar2 == '<') //if the next character is a '<', add to backspace counter
{
bscount++;
}
else
{
result.push(catchvar1);
result.push(catchvar2);
}
}
else //if the popped character is not a '-'
{
if (bscount = 0) //if bscount = 0, popped character gets pushed onto new stack
{
result.push(catchvar1);
}
else //if bscount is >0, bscount gets decremented and popped character
{ //stays popped off
bscount--;
}
}
}
char resultvar;
result.pop(resultvar);
cout << resultvar << endl;
}
Also, here are my implementations for the pop and push functions, in case there is something awry in it:
template <class stackElem, int maxSize>
bool stack<stackElem, maxSize>::push(const stackElem &item)
{
top++;
elements[top] = item;
}
template <class stackElem, int maxSize>
bool stack<stackElem, maxSize>::pop(stackElem &item)
{
item = elements[top];
top--;
}