stack2.cpp

来自「Think in C++ 第二版源码」· C++ 代码 · 共 56 行

CPP
56
字号
//: C20:Stack2.cpp

// From Thinking in C++, 2nd Edition

// Available at http://www.BruceEckel.com

// (c) Bruce Eckel 1999

// Copyright notice in Copyright.txt

// Converting a list to a stack

#include "../require.h"

#include <iostream>

#include <fstream>

#include <stack>

#include <list>

#include <string>

using namespace std;



// Expects a stack:

template<class Stk>

void stackOut(Stk& s, ostream& os = cout) {

  while(!s.empty()) {

    os << s.top() << "\n";

    s.pop();

  }

}



class Line {

  string line; // Without leading spaces

  int lspaces; // Number of leading spaces

public:

  Line(string s) : line(s) {

    lspaces = line.find_first_not_of(' ');

    if(lspaces == string::npos)

      lspaces = 0;

    line = line.substr(lspaces);

  }

  friend ostream& 

  operator<<(ostream& os, const Line& l) {

    for(int i = 0; i < l.lspaces; i++)

      os << ' ';

    return os << l.line;

  }

  // Other functions here...

};



int main(int argc, char* argv[]) {

  requireArgs(argc, 1); // File name is argument

  ifstream in(argv[1]);

  assure(in, argv[1]);

  list<Line> lines;

  // Read file and store lines in the list:

  string s;

  while(getline(in, s)) 

    lines.push_front(s);

  // Turn the list into a stack for printing:

  stack<Line, list<Line> > stk(lines);

  stackOut(stk);

} ///:~

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?