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.
should be:
Also, your read-loop logic is wrong. It should be:
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:
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.