File Reverser C++
File Reverser
Write a program that opens a text file and reads its contents into a stack of characters.
The program should then pop the characters from the stack and save them in a second
text file. The order of the characters saved in the second file should be the reverse of
their order in the first file.
Answer:
// File Reverser #include <iostream> #include <fstream> #include "DynStack.h" using namespace std; int main() { // Create an input file stream object. fstream file1("file1.txt", ios::in); // Create an output file stream object. fstream file2("file2.txt", ios::out); // Create a stack to hold characters. DynStack<char> stack; char catchChar, ch; // Read the characters from file #1 // and push them onto the stack. file1.get(catchChar); while (!file1.eof()) { stack.push(catchChar); file1.get(catchChar); } // Close file #1. file1.close(); // Pop the characters from the stack // and write them to file #2. while (!stack.isEmpty()) { stack.pop(ch); file2.put(ch); } // Close file #2. file2.close(); // Open file #2 again. file2.open("file2.txt", ios::in); // Read the characters from file #2 // and display them. file2.get(ch); while (!file2.eof()) { cout << ch; file2.get(ch); } // Close file #2. file2.close(); cout << endl; return 0; }
// DynStack template template <class T> class DynStack { private: struct StackNode { T value; StackNode *next; }; StackNode *top; public: DynStack() { top = NULL; } void push(T); void pop(T &); bool isEmpty(); }; //********************************************************* // Member function push pushes the argument onto * // the stack. * //********************************************************* template <class T> void DynStack<T>::push(T num) { StackNode *newNode; // Allocate a new node & store Num newNode = new StackNode; newNode->value = num; // If there are no nodes in the list // make newNode the first node if (isEmpty()) { top = newNode; newNode->next = NULL; } else // Otherwise, insert NewNode before top { newNode->next = top; top = newNode; } } //********************************************************* // Member function pop pops the value at the top * // of the stack off, and copies it into the variable * // passed as an argument. * //********************************************************* template <class T> void DynStack<T>::pop(T &num) { StackNode *temp; if (isEmpty()) { cout << "The stack is empty.\n"; return; } else // pop value off top of stack { num = top->value; temp = top->next; delete top; top = temp; } } //********************************************************* // Member funciton isEmpty returns true if the stack * // is empty, or false otherwise. * //********************************************************* template <class T> bool DynStack<T>::isEmpty() { if (!top) return true; else return false; }
Leave a reply