首页 > 解决方案 > 无法读取通过引用传递给构造函数的 ifstream

问题描述

我不明白为什么我的 ifstream 不能在我的课堂上阅读。在 main.cpp 从流中读取工作正常,但是当我通过引用 c'tor 传递 ifstream 时,我无法从中读取。该程序编译良好,但“输入文件”似乎为空。在控制台中,我只看到一次来自 main.cpp 的 .txt 内容。

我通过 ifstream 做错了吗?

主.cpp:

#include <iostream>
#include <fstream>
#include <string>
#include "RAM.h"

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

    std::ifstream input;
    input.open("\\path\\orders.txt");

    std::string line;
    while (std::getline(input, line))
    {
        std::cout << line << std::endl;
    }

    RAM machine(input);
}

内存.h:

#pragma once
#include <fstream>

class RAM
{
    private:
        std::ifstream& inputfile;

    public:
        RAM(std::ifstream&); 
        ~RAM();
};

内存.cpp:

#include "RAM.h"
#include <iostream>
#include <fstream>
#include <string>

RAM::RAM(std::ifstream &in) : inputfile(in){


    std::string line;

    while (std::getline(inputfile, line))
    {
        std::cout << line << std::endl;
    }
}

RAM::~RAM() {

}

订单.txt:

ADD 5
SUB 7
HLT 99

标签: c++

解决方案


输入文件似乎是空的,因为您已经读取了main(). 换句话说,你在文件的末尾:

// File just opened, at position 0.

std::string line;
while (std::getline(input, line))
{
    std::cout << line << std::endl;
}

// File fully read, at end of file.

RAM machine(input);

如果您想重新阅读它,您需要在尝试重新阅读构造函数之前回到起点,例如:

inputfile.seekg(0);

推荐阅读