tags:

views:

232

answers:

2

Please help I'm new to C++

Using stacks Implementation

I should read a sample text file containing:

text file
begining to end
return text

And return a text file reading:

return text
begining to end
test file

This is the sample code to test the implementation:

#include <iostream>
#include <fstream>
#include <string>
#include "stack1.h"
using namespace std

void reverse (ifstream & infile, ofstream & outfile);  //function prototype

int main () {

ifstream infile;  // declaring a file for input
ofstream outfile; // declaring a file for output
infile.open ("c:\\myInputFile.txt");  

 if (!infile)  { cout << "File could not be opened.  Program terminated." << endl;
           return 1;    // terminates program
         }
 outfile.open ("c:\\myOutfile.txt");
 reverse (infile, outfile);
 infile.close();
outfile.close();
 return 0;
 }

void reverse (ifstream & infile, ofstream & outfile) {
 string s;
 stack<string> mystack;

 getline(infile, s); // try to read a line of text from the file
 while (!infile) { // while not end of file
  mystack.push(s);
  getline(infile, s); // try to read another line
  }
 while (! mystack.isEmpty() ) {
  s = mystack.pop();
  outfile << s << endl; // write s to the outfile
  }
 }
+2  A: 

How about:

//open infile in and outfile out.
std::stack<std::string> lines;
std::string temp;
while(std::getline(in, temp)) lines.push(temp);
while(!lines.empty()) outfile << lines.pop() << std::endl;

I'm unsure exactly what your question is here though.

Edit: changed push_back() and pop_back to push() and pop() respectively (because those are what std::stack provides).

Billy ONeal
I agree what is your question. Seems the code you have already should work you just need to pop the stack at the end and display all it's contents to view the file in reverse.
ferrari fan
@ferrari fan: How's the updated code?
Billy ONeal
@BillyONeal, This did not compile with VS2008. `lines.pop()` returns `void` as per MSDN. I had to use `lines.top()`.
Vulcan Eager
@Agnel: Doh! Used to using plain Vectors because stack is just an adaptor in top of vector. @Jerry: Thanks for fixing the code.
Billy ONeal
+1  A: 

Get rid of the !

while (infile) { // while not end of file

You could use std::stack instead of whatever is in "stack1.h".

Dan