Home > Back-end >  Is there a way to make a single loop for two different variables?
Is there a way to make a single loop for two different variables?

Time:10-16

I am looking for a way to make a single loop for two variables. I have a "p1" (player 1) and a "p2". Both have the particularity to use the same loop to have a certain number of spaces. Is there a solution to make a single loop instead of creating two? Here is the loop in question for the player one:

    for (string::size_type i = 1; i < (SIZE - p1.name.length()) / 2; i  ) {
   
        cout << " ";
}

CodePudding user response:

Yes, you separate the initialization and updates with commas (,) and convert the condition to a compound one.

for (string::size_type i = 1, string::size_type j = 1; i < (SIZE - p1.name.length()) / 2 && j < (SIZE - p2.name.length()) / 2; i  , j  ) {
   
        cout << " ";
}
  •  Tags:  
  • c
  • Related