gpt4 book ai didi

c++ - ifstream 在我的代码中不起作用?

转载 作者:行者123 更新时间:2023-11-30 04:14:15 25 4
gpt4 key购买 nike

我的代码没有按预期输出 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;
}
};

最佳答案

嗯……这取决于。 Stack 有什么作用?它打印了多少个 “1” - 一个还是十个?

Stack 看起来很奇怪:如果 pop 是在 string 上模板化的,为什么还需要转换它?我相信 pop 不会返回您认为它返回的内容。

编辑

我复制了你的代码,我得到了 10 个带线的“1”。我实际上以相反的顺序得到了文件的最后 10 行(对你来说是很好的练习 - 弄清楚,它非常有意义)。

如果你没有得到任何行,只有 1 个“1”,我的猜测是程序没有找到文件(可执行文件是从不同的目录执行的)

尝试将打印添加到 getline 循环中,看看您实际读取了多少行。

关于c++ - ifstream 在我的代码中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009118/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com