I'm trying to read from an input file into a stack, and then output the reverse of that file. To do this correctly, I need the spaces in the file as well. Can I push a space into the stack? I must be doing it wrong. Here is what I have. Can anyone tell me what I've done wrong?
Thanks
// Main program begins
int main()
{
openOutput(); // Open output first so it exists to print out on
openInput(); // Open input to read from
printHeader(); // Print assignment header
Stack stack1; // Creates stack to hold input file characters
char value; // Variable to hold character
cout << "This is the Reverse of the file I copied: " << endl;
outfile << "This is the Reverse of the file I copied: " << endl;
infile >> value; // Read in first character
while(!infile.eof()) // While we are not at the end of the file
{
if (isspace(value)) // If I read in a space, '\n, or CR
{
stack1.push(" ");// Push a space onto stack
}
else // Otherwise, it must be a character
{
stack1.push(value); // Add character to the stack
infile >> value; // Read in next character
}
}
cout << "This stack holds " << stack1.size() << " characters. " << endl;
for (int i = 0; i < stack1.size(); i++)
{
while (!stack1.is_empty())// While in stack
{
cout << stack1.top(); // Print top value in stack
outfile << stack1.top();// Echo
stack1.pop(); // Delete it, and move on to next value
}
}
return 0;
}
@Volatile Pulse
Resize what, most stacks Ive seen where implemented as linked lists so no resizing. To OP why not just push the space char onto the stack (' ').
@OP: You are not reading the spaces and line breaks. infile >> value; will skip them.
You may want to use infile.get(value) instead.
Also, don't loop on eof but on the reading operation.
If you've got another issues, at least describe them.
@naraku9333: Implementing stacks or queues with arrays is quite simple. Try it.
Okay, one more question: I got that to work, using
1 2 3 4 5 6 7 8 9 10 11 12 13
if (infile.peek() == isspace(value)) // Is next character whitespace?
infile.get(value); // Read in first character
while(!infile.eof()) // While we are not at the end of the file
{
if (infile.peek() == isspace(value))// Is next character whitespace?
{
stack1.push(' '); // If it is, push blank onto stack
}
else // Otherwise
{
stack1.push(value); // Add character to the stack
infile.get(value); // Read in next character
}
for that part. So, when I run the program, the screen that pops up is correct. The problem now is that the output file it saves to, looks like all Chinese characters. You know what I mean. Why did it do that, and how do I fix it? Do you need the entire program to see?