home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C20 / Stack2.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.3 KB  |  56 lines

  1. //: C20:Stack2.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Converting a list to a stack
  7. #include "../require.h"
  8. #include <iostream>
  9. #include <fstream>
  10. #include <stack>
  11. #include <list>
  12. #include <string>
  13. using namespace std;
  14.  
  15. // Expects a stack:
  16. template<class Stk>
  17. void stackOut(Stk& s, ostream& os = cout) {
  18.   while(!s.empty()) {
  19.     os << s.top() << "\n";
  20.     s.pop();
  21.   }
  22. }
  23.  
  24. class Line {
  25.   string line; // Without leading spaces
  26.   int lspaces; // Number of leading spaces
  27. public:
  28.   Line(string s) : line(s) {
  29.     lspaces = line.find_first_not_of(' ');
  30.     if(lspaces == string::npos)
  31.       lspaces = 0;
  32.     line = line.substr(lspaces);
  33.   }
  34.   friend ostream& 
  35.   operator<<(ostream& os, const Line& l) {
  36.     for(int i = 0; i < l.lspaces; i++)
  37.       os << ' ';
  38.     return os << l.line;
  39.   }
  40.   // Other functions here...
  41. };
  42.  
  43. int main(int argc, char* argv[]) {
  44.   requireArgs(argc, 1); // File name is argument
  45.   ifstream in(argv[1]);
  46.   assure(in, argv[1]);
  47.   list<Line> lines;
  48.   // Read file and store lines in the list:
  49.   string s;
  50.   while(getline(in, s)) 
  51.     lines.push_front(s);
  52.   // Turn the list into a stack for printing:
  53.   stack<Line, list<Line> > stk(lines);
  54.   stackOut(stk);
  55. } ///:~
  56.