patterncppModerate
Is this the right way to read every line?
Viewed 0 times
thisthelinereadwayeveryright
Problem
I am never to sure when it comes to
Could anyone tell me if I am doing it right?
ifstream and reading lines. I am often confused with the good(), bad(), eof() and so on.Could anyone tell me if I am doing it right?
int parseLine(std::ifstream & _file)
{
while( std::getline( _file, line, '\n' ).good() && !_file.eof() )
{
// some treatment
}
return 0;
}Solution
Too complicated. Just say:
The function
Also, the function shouldn't be called "parseLine", but "parseAllLines" or "parseStream".
for (std::string line; std::getline(_file, line); )
{
// process "line"
}The function
std::getline, like most iostreams operations, returns a reference to the stream object itself, which can be evaluated in a boolean context to tell you whether it is still good, i.e. whether the extraction operation succeeded.Also, the function shouldn't be called "parseLine", but "parseAllLines" or "parseStream".
Code Snippets
for (std::string line; std::getline(_file, line); )
{
// process "line"
}Context
StackExchange Code Review Q#14790, answer score: 11
Revisions (0)
No revisions yet.