dimanche 28 novembre 2021

C++ istream_iterator doesn't work after initial use

I'm learning about C++ iterators and I'm having trouble with the following piece of code. It simply reads in a text file data.txt that has a series of integers in it, and prints the contents to the console, twice. The initial print loop works fine, but the second one stops after the first entry. Why does this happen?

#include <iterator>  // 
#include <iostream>  // 
#include <fstream>   // 

int main(void)
{
    std::ifstream ifstream_0("data.txt");
    std::istream_iterator<int> istream_iterator_0(ifstream_0), end;
    
    // print out contents
    for (auto it = istream_iterator_0; it != end; it++) 
    {
        std::cout << *it << std::endl;
    } 

    // print out contents again, but this stops after the first entry
    for (auto it = istream_iterator_0; it != end; it++) 
    {
        std::cout << *it << std::endl;
    }
}

data.txt looks like this:

1 2 3 4 5 6

The output of the program is the following:

1
2
3
4
5
6
1

My question is, why does the second print loop stop after the first entry, "1" ?

Aucun commentaire:

Enregistrer un commentaire