PascalVKooten
PascalVKooten

Reputation: 21481

passing a std::ifstream to function as a pointer

I am sorry for the beginner question, but I do not understand what is going wrong with the ifstream. Is it not possible to send it to a function like a pointer (see below)?

The idea is that as a side effect I want the ifstream to move on while the function is being called, hence trying to send it as a pointer.

  string ID, Title, Body;

  ifstream ifs(filename);   // std::string filename

  while(ifs.good()) {
     ID = findCell(ifs)
     Title = findCell(ifs)
     Body = findCell(ifs)  
  }
}
std::string findCell(ifstream *ifs)   // changed to &
{
    char c;
    bool isPreviousQuote;
    string str;
    while(ifs.good())
    {
        ifs.read(c, 1);   // error now shows up here

        if (c == "\n") {
           break;
        }
        str.push_back(c);
    } 
    return str;
}

The error is:

invalid user-defined conversion from 'std::ifstream {aka std::basic_ifstream<char>}' 
to 'std::ifstream* {aka std::basic_ifstream<char>*}' [-fpermissive]

Upvotes: 0

Views: 7445

Answers (1)

LihO
LihO

Reputation: 42133

Your function takes a pointer to std::ifstream object:

std::string findCell(ifstream *ifs)

Pointers should be initialized using the address of a memory block that they will point to.
In this case an address of ifs retrieved with &:

Title = findCell(&ifs);

Yet even better since findCell function requires the existence of the ifstream, it is much cleaner and more reasonable to pass by reference:

std::string findCell(std::ifstream& ifs) { ... }
...
Title = findCell(ifs);

Upvotes: 5

Related Questions