簡體   English   中英

無法讀取通過引用傳遞給構造函數的 ifstream

[英]ifstream passed by reference to constructor can't be read

我不明白為什么我的 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

輸入文件似乎是空的,因為您已經讀取了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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM