Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a reference to std::ifstream as parameter

I'm trying to write a function with an ifstream& argument.

void word_transform(ifstream & infile)
{
    infile("content.txt");
    //etc
}

which gave me an error:

Type 'ifstream' (aka 'basic_ifstream ') does not provide a call operator.

Can you please me what's wrong?

like image 299
Newbie Avatar asked Jan 09 '23 06:01

Newbie


2 Answers

call operator is a function like operator()( params ) allowing to use the syntax myObject( params ).

So, when you write infile(...), you are trying to us a call operator.

What you are trying to do is to open a file, use the open method:

void word_transform(ifstream & infile)
{
    infile.open("content.txt",std::ios_base::in);
    if ( infile.is_open() )
        infile << "hello";
    infile.close();
}

But, as commented, it does not really make sense to pass infile reference to such a function. You may consider:

void word_transform(istream& infile)
{
    infile << "hello";
}

int main()
{
    ifstream infile;
    infile.open("content.txt",std::ios_base::in);
    if ( infile.is_open() )
        word_transform( infile );
    infile.close();
    return 0;
}

Or:

void word_transform()
{
    ifstream infile;
    infile.open("content.txt",std::ios_base::in);
    if ( infile.is_open() )
        infile << "hello";
    infile.close();
}

int main()
{
    word_transform();
    return 0;
}
like image 63
jpo38 Avatar answered Jan 18 '23 23:01

jpo38


You attempt to call operator() on your parameter. That will not work. Are you trying to open a file? If you get an ifstream as parameter, it should be open from the start because you opened it outside your function. Passing a stream and then opening it inside your function does not make sense.

void word_transform(std::ifstream& infile)
{
    // read something from infile
}

int main()
{
   std::ifstream file("content.txt");

   // error checks

   word_transform(file);

   return 0;
}
like image 22
nvoigt Avatar answered Jan 18 '23 23:01

nvoigt