简体   繁体   中英

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, eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM