简体   繁体   中英

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. Basically I'm trying to sort a list of numbers using a heap ADT implemented with an array.

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. The compiler can't recognize the operator ">>" between an 'int' and an 'ifstream' object. However, strangely enough, if I write that same while loop inside main(), it'll work just fine. Also of note is that if I remove the while loop, the compiler returns no errors. Meaning, simply the act of passing the ifstream object from main to buildHeap is OK.

Please avoid suggesting alternative ways of achieving this. I was asked to not use any special fstream functions like 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:

heap->buildHeap(infile);
//...
void HeapSort::buildHeap(ifstream& infile) 
{
    int data;
    while (infile >> data) { ... }
    infile.close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM