Write a program that opens a text file called input.txt and reads its contents i
ID: 3821294 • Letter: W
Question
Write a program that opens a text file called input.txt 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 called output.txt. The order of the characters saved in the second file should be the reverse of their order in the first file. We don’t know the text file length.
Input.txt
output.txt
Directions:
Finish
Stack & Stack::operator=(const Stack & original)
{
// write code here, refer copy construct
}
Explanation / Answer
Here is the program for the above scenario:
#include <iostream>
#include <fstream>
#include "CharStack.h"
using namespace std;
int main()
{
CharStack stack;
char ch;
ifstream inputFile;
ofstream outputFile;
inputFile.open("letters.txt");
if (!inputFile)
{
cout << "The file cannot be opened. ";
exit(1);
}
while (inputFile.get(ch))
{
stack.push(ch);
}
inputFile.close();
outputFile.open("testoutput.txt");
if (!outputFile)
{
cout << "The file cannot be opened. ";
exit(1);
}
while (!stack.isEmpty())
{
stack.pop(ch);
outputFile.put(ch);
}
outputFile.close();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.