[英]How do I read from an input file after passing the ifstream object to a function?
as the title suggests, I am having a problem with not being able to read from an input file after passing the ifstream object to a class function. 顾名思义,将ifstream对象传递给类函数后,我无法读取输入文件时遇到了问题。 Basically I'm trying to sort a list of numbers using a heap ADT implemented with an array.
基本上,我正在尝试使用通过数组实现的堆ADT对数字列表进行排序。
int main() {
ifstream infile("input.txt");
HeapSort* heap = new HeapSort(20); // creates a heap (array) with size 20
heap->buildHeap(&infile);
return 0;
}
void HeapSort::buildHeap(ifstream* infile) {
int data;
while (infile >> data) {cout << data << endl;}
infile->close();
}
the error occurs in the conditional of the while loop inside buildHeap. 该错误发生在buildHeap中的while循环的条件下。 The compiler can't recognize the operator ">>" between an 'int' and an 'ifstream' object.
编译器无法识别“ int”和“ ifstream”对象之间的运算符“ >>”。 However, strangely enough, if I write that same while loop inside main(), it'll work just fine.
但是,很奇怪的是,如果我在main()中编写相同的while循环,它将很好地工作。 Also of note is that if I remove the while loop, the compiler returns no errors.
还要注意的是,如果删除while循环,则编译器将不返回任何错误。 Meaning, simply the act of passing the ifstream object from main to buildHeap is OK.
意思是,简单地将ifstream对象从main传递到buildHeap即可。
Please avoid suggesting alternative ways of achieving this. 请避免建议实现此目的的其他方法。 I was asked to not use any special fstream functions like eof().
我被要求不要使用任何特殊的fstream函数,例如eof()。 I can only use the ">>" operator to read from the desired file.
我只能使用“ >>”运算符来读取所需的文件。
You're passing a pointer to a stream, so you need to dereference it: 您正在传递指向流的指针,因此需要取消引用它:
while (*infile >> data)
If you want your code to look like what you say you did in main
, then you pass a reference: 如果您希望代码看起来像您在
main
所做的一样,那么您可以传递一个引用:
heap->buildHeap(infile);
//...
void HeapSort::buildHeap(ifstream& infile)
{
int data;
while (infile >> data) { ... }
infile.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.