rajat
rajat

Reputation: 3553

Reading a text file line by line in C++

How does the code below work ? where is the counter for the for-loop and how can i reset the counter to line number 0.

for (std::string line;std::getline(ifs, line); )
{
}

Upvotes: 2

Views: 424

Answers (3)

Mark Pervovskiy
Mark Pervovskiy

Reputation: 1123

And to reset the counter to line number 0 (i.e. to the beginning of stream) you should use

ifs.seekg (0, ios::beg);

Upvotes: 1

Branko Dimitrijevic
Branko Dimitrijevic

Reputation: 52137

Your for loop is equivalent to:

{
    std::string line;
    while (std::getline(ifs, line)) {
    }
}

In other words: "keep iterating as long as getline returns true".

Upvotes: 3

Borgleader
Borgleader

Reputation: 15916

There is no need for a counter. This is equivalent to

std::string line;
while(getline(ifs, line))
{
}

There are methods to move the input iterator back to the beginning of the file. Something like: ifs.seekg(0, std::ios::beg); should do the trick.

Upvotes: 6

Related Questions