我的代码没有像我预期的那样输出 main.cpp 的前 10 行。请告诉我为什么。谢谢!
#include "TStack.h"
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[]) {
ifstream in("main.cpp");
Stack<string> textlines;
string line;
while (getline(in, line)) {
textlines.push(new string(line));
}
string* s;
for (int i = 0; i < 10; i++) {
cout << "1" << endl;
if((s = (string*)textlines.pop())==0) break;
cout << *s << endl;
delete s;
}
}
以下是表头。以下是表头。以下是表头。以下是表头。以下是表头。
#ifndef stackex_TStack_h
#define stackex_TStack_h
template <class T>
class Stack {
struct Link{
T* data;
Link* next;
Link(T* dat, Link* nxt): data(dat), next(nxt) {}
}* head;
public:
Stack() : head(0) {}
~Stack() {
while(head)
delete pop();
}
void push(T* dat) {
head = new Link(dat, head);
}
T* peek() const {
return head ? head->data : 0;
}
T* pop() {
if(head == 0) return 0;
T* result = head->data;
Link* oldHead = head;
head = head->next;
delete oldHead;
return result;
}
};