0

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?

kaiyu wei
  • 431
  • 2
  • 5
  • 14
  • it reads from the current position of the stream? – Alan Birtles Jan 13 '22 at 10:37
  • It's because it reads from a [stream](https://stackoverflow.com/questions/12145357/what-is-a-stream-in-c). The stream (`ifs` in this case) is passed by reference, so it's always referring to the same object which gets updated. – Thomas Jan 13 '22 at 10:37
  • the `ifstream` has an index internally to remember where it is in the file. – mch Jan 13 '22 at 10:38

1 Answers1

2

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.

Dúthomhas
  • 8,200
  • 2
  • 17
  • 39