Hi,

I have to make a program that takes an input text file and reverses the contents of that file, and outputs that into another text file. I am new to stacks, but what I have so far nothing happens, it just outputs a blank text file. I just wanted to check what is missing here.

Thanks.

#include <iostream>
#include <fstream>
#include <stack>
#include <string>

using namespace std;

int main() {

	stack<string> myStack;	
        string character;
	ifstream infile;
	ofstream outfile;
	
	infile.open("TextIn.txt");
	outfile.open("TextOut.txt");
	
  
    while (infile) 
	{
        myStack.push(character);
        }


    while (!myStack.empty()) 
	{
       outfile << myStack.top() << endl;
       myStack.pop();            
        }

	infile.close();
	outfile.close();

    return 0;
}

Recommended Answers

All 4 Replies

lines 19 through 22 are not actually doing anything. you need to get the words from the file in order to push them into the stack. To get the word from the file into your stack you will need to do something like this.

stack<string> Stack;
string word;
ifstream fin("text.txt");
while (fin >> word)
     Stack.push(word);

Thanks I got it to read the whole file now, but the contents in the file have not been reversed. It just made a copy of the first text file. I tried changing the pop and top operations for the stack but it still the same. How can I fix that ?

#include <iostream>
#include <fstream>
#include <stack>
#include <string>

using namespace std;

int main() {

	stack<string> myStack;	
    string character;
	ifstream infile;
	ofstream outfile;
	
	infile.open("TextIn.txt");
	outfile.open("TextOut.txt");
	
  
 while (getline(infile, character)) 
 {
        myStack.push(character);
 

    while (!myStack.empty()) 
	{
       outfile << myStack.top() << endl;
       myStack.pop();           
    }


 }


	infile.close();
	outfile.close();

    return 0;
}

you need to seperate your while loops.

// you have
while (getline(infile, character)) 
 {
        myStack.push(character);
 

    while (!myStack.empty()) 
	{
       outfile << myStack.top() << endl;
       myStack.pop();           
    }


 }

// should be

while (getline(infile, character)) 
{
        myStack.push(character);
}
 

while (!myStack.empty()) 
{
       outfile << myStack.top() << endl;
       myStack.pop();           
}

also im not sure if you want to use getline. if you want to get each word in the file into its own element in the stack you will have to use ifstream's >> operator like i used in my example.

}

Thanks for the help it works now.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.