c++ - 无法读取通过引用传递给构造函数的 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
解决方案
输入文件似乎是空的,因为您已经读取了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);
推荐阅读
- c++ - constexpr 与匿名命名空间
- javascript - 如何使输入字段只接受数字
- c# - 是否可以从不活跃的广告中检索 Facebook 潜在客户?
- spring - 如何在 spring-boot 应用程序启动期间创建许多 kafka 主题?
- c++ - Windows 10 下 Winhttp SSL 的问题
- extjs - 如何在组合框中添加树
- java - 如何修复休眠异常 - 不要更改对启用了删除孤儿的集合的引用
- linux - 从每个数组中交替打印十个值,直到两者都为空
- python - 如何在 Pyspark 中将字符串更改为时间戳?
- variables - 如何处理源数据库中名称相同的字段,仅按标签名称区分?