I cannot figure out why getline is working in one X-Code project but not in another. The error “No matching function for call to ‘getline’.
When I make a single cpp file it compiles with no issues.
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( myfile.good() )
{
getline (myfile,line);
cout << line << endl;
}
myfile.close();
}
else cout << "Unable to open file";
return 0;
}
I would really appreciate some assistance. I am just learning and the example above came from my test book.
The code is noisy and incorrect. The correct standard idiom is like this:
Correctness:
You must check the success of the input operation before consuming the input. To do otherwise may be UB, and certainly never correct.
[Thanks @James for pointing this out:]
good()doesn’t check if a file was opened. You could use either!myfile.fail()ormyfile.is_open(), but just don’t bother (see below).Noise:
The
ifstreamconstructor takes the filename and opens the file already. Use it.The
ifstreamcleans up in its destructor, no need to do that explicitly. Use tight scoping to close the file as soon as you’re done with it.Don’t leak
lineinto the ambient scope if you don’t need it.No need for
good()(or any of the correct alternatives). Just evaluate theifstreamobject in a boolean context to see if the file was opened successfully.