Search code examples
c++functioniostreamifstreamgetline

how does getline() read a multiple-line file in loops?


I have some confusion about the use of std::getline function. see the following code:

#include <sstream>
#include <string>
std::ifstream ifs(filename);
std::string line;

while (std::getline(ifs, line))
{
  //...//
}

for ( std::string s; getline(ifs, s)){
  //...//
}

For both of the while loop and the for loop, it seems like each time in a new iteration, the "geline" is reading a new line, e.g. if we have a file storing:

1 2
3 4
5 6

then in the first iteration, getline reads 1 2 , then 3 4 in the next iteration... so, how does it know from which line it should start reading when an iteration starts?


Solution

  • A file stream is a source of bytes (“characters”). Each time you read a character from the file the file get pointer is advanced to the next character to read.

    That is, each time you read, you get the next unread character.

    std::getline() simply reads characters until it gets the delimiter value (which is '\n' by default). Hence each call to getline() gets the next line in the file.