Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spot the error in this file reading code (C++)

Tags:

c++

file-io

Can anyone please tell my why this method won't compile?

void Statistics::readFromFile(string filename)
{
    string line;
    ifstream myfile (filename);
    if (myfile.is_open())
    {
        while (! myfile.eof() )
        {
            getline (myfile,line);
            cout << line << endl;
        }
        myfile.close();
    }

    else cout << "Unable to open file"; 

}

Should work, right? Yet, I always get the following error message:

Line Location Statistics.cpp:15: error:
   no matching function for call to
   'std::basic_ifstream<char, std::char_traits<char> >::
      basic_ifstream(std::string*)'

any help would be greatly appreciated.

like image 429
winsmith Avatar asked Mar 20 '26 03:03

winsmith


2 Answers

ifstream myfile (filename);

should be:

ifstream myfile (filename.c_str() );

Also, your read-loop logic is wrong. It should be:

while ( getline( myfile,line ) ){
   cout << line << endl;
}

The eof() function that you are using is only meaningful after you have tried to read read something.

To see why this makes a difference, consider the simple code:

int main() {
    string s; 
    while( ! cin.eof() ) {
        getline( cin, s );
        cout << "line is  "<< s << endl;
    }
}

If you run this and type ctrl-Z or ctrl-D to indicate EOF immediately, the cout will be performed even though no line has actually been input (because of the EOF). In general, the eof() function is not very useful, and you should instead test the return value of functions like getline() or the stream extraction operators.

Read the compiler error:

no matching function for call to 'std::basic_ifstream >::basic_ifstream(std::string*)

No matching function for call to: It can't find the function you're trying to call

std::basic_ifstream >:: - a member function of ifstream

:basic_ifstream(std::string*) - the constructor which takes a string pointer as its argument

So you try to create an ifstream by passing a string pointer to its constructor. And it can't find a constructor that accepts such an argument.

Since you're not passing a string pointer in the above, the code you've posted must be different from your actual code. Always copy/paste when asking about code. Typos make it impossible to figure out the problem. In any case, as I recall, the constructor does not accept a string argument, but only a const char*. So filename.c_str() should do the trick

Apart from that, you can do this a lot simpler:

ifstream myfile (filename);
    std::copy(std::istream_itrator<std::string>(myfile),
              std::istream_itrator<std::string>(),
              std::ostream_iterator<std::string>(std::cout));
}
like image 36
jalf Avatar answered Mar 21 '26 17:03

jalf