-1

I have coding experience in C# but I am beginner in c++.

How to read file line by line using below "for loop".

for (int i = 0; i < count; i++)
{
}

I found this piece of code but I couldn't understand.

for (string line = ""; getline(infile, line); )
    {
        //do something with the line
    }
TulMagar
  • 39
  • 8
  • `getline(infile, line)` reads a line at a time. When used as the "test" condition (either in a `while` or `for` loop) you loop reading lines until the stream-state is no longer good (usual change due to end-of-file). So the loop, simply uses `getline()` as the test condition and reads a line each time the test clause is checked. – David C. Rankin Oct 01 '20 at 08:44

2 Answers2

2

As you know the for loop runs until the middle part returns false, which is:

getline(infile, line)

getline in this case returns false if there's nothing more to read so this will loop every line of the file assuming infile is the opened file as an fstream.

Hatted Rooster
  • 33,170
  • 5
  • 52
  • 104
2

The standard streams in C++ can be used in conditions to check if they have an error or have reached the end of the file.

And the std::getline function returns (a reference to) the stream passed as the first argument.

This can be combined, so the std::getline call can be used in a condition, as shown in the second piece of code in your question.

Some programmer dude
  • 363,249
  • 31
  • 351
  • 550