Hakim Muhaimin
Hakim Muhaimin

Reputation: 87

How to repeat and print 2 or more for loops?

I am trying to print out values from my txt file. I created a struct so that I can easily search for the element in the txt file. So for my first for loop I searched for "CC" as the first option and then I print. It works. However when I try copy the same loop and search for something else, lets say "SN" so that I can print all the values with SN as the first option, the second and subsequent loop does not print. It only works if I copy the long code again and create a new function but I do not want to do that because I try to keep it compact.

cout << "\nCC Students:" << endl;
int cc = 0;
for (; it != v.end(); it++)
{
    if ((*it).First == "CC"){
        cout << (*it).Name << " " << (*it).GPA << "\n";
        if (++cc == 10)
            break;
    }
} // can print


cout << "\nSN Students:" << endl;
int sn = 0;
for (; it != v.end(); it++)
{
    if ((*it).First == "SN"){
        cout << (*it).Name << " " << (*it).GPA << "\n";
        if (++sn == 10)
            break;
    }
} // cannot print

Upvotes: 1

Views: 118

Answers (1)

Mureinik
Mureinik

Reputation: 311163

The question doesn't show the initialization of it, but from the context it seems to be an iterator on v. The first loop exhausts the iterator, and terminates when it reaches v.end(). When you start another loop, you should reinitialize it to v.begin(), e.g.:

for (it = v.begin(); it != v.end(); it++)
// Here ^

Upvotes: 2

Related Questions