Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading