2

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); )
{
}

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

4 Comments

@rajat Seek through the file.
I found a easier way , i just close and reopen the file . > ifs.close();ifs.open(filename);
@rajat that may be 'easier', but it's a hack - reopening is slower than seeking. You do want to seek.
@rajat ::shudder:: Use seek. Just one system call instead of two, plus close/re-open introduces a race condition, and while errors related to that may be rare they will be effectively impossible to debug. For instance, on unix-like systems the file may have been deleted from the command line in the mean time and close and re-open will fail (because the file will be gone), while seeking will still work.
1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.