Set numbers in a for loop

If I have this piece of code, how could I get it to output a number before each line. So that output would be something like this,

1 Barack            Obama            
2 Micheal           Phelps
3 Britney           Spears


1
2
3
4
5
for(auto& e : persons)
    {  
        cout << left << setw(20) << e.firstname;
        cout << setw(20) << e.lastname;
    }
Last edited on
How about this:
1
2
3
4
5
6
7
    int i=1;
    for(auto& e : persons)
    {  
        cout << left <<  i << ' ' << setw(20) << e.firstname;
        cout << setw(20) << e.lastname;
        i++;
    }
1
2
3
4
5
6
7
    for (auto& e : persons)
    {  
        static int n = 1;
        cout << right << setw(3)  << n++ << "  "
             << left  << setw(20) << e.firstname
             << setw(20) << e.lastname << '\n';
    } 

Declare n as static so it retains its value from one iteration to the next. (You could declare it outside the loop, but that is cluttering the outer scope with unnecessary variables).
Topic archived. No new replies allowed.