Hi. The other day, I decided to write a small application for my favorite game just to see if I could. So the basic idea is that you input 5 player's names, and the application will randomly assign them a character to play.
Anyway, here's my question. So far, when asking for the player's name, here is what I have (I store each player's name in it's own variable):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
cout<< "Input the name of Player 1: \n";
cin>> Player1;
endl (cout);
cout<< "Input the name of Player 2: \n";
cin>> Player2;
endl (cout);
cout<< "Input the name of Player 3: \n";
cin>> Player3;
endl (cout);
cout<< "Input the name of Player 4: \n";
cin>> Player4;
endl (cout);
cout<< "Input the name of Player 5: \n";
cin>> Player5;
endl (cout);
I was wondering if there is any way to consolidate that down to maybe one or two statements, rather than having to write it out 5 times? I thought about using a for loops to do it, but I wasn't sure if it was even possible.
#include <iostream>
#include <string>
std::string get_player_name( int n )
{
std::cout << "Input the name of Player " << n << ": " ;
std::string name ;
std::getline( std::cin, name ) ;
return name ;
}
int main()
{
enum { NPLAYERS = 5 } ;
std::string player_names[NPLAYERS] ;
for( int i = 0 ; i < NPLAYERS ; ++i ) player_names[i] = get_player_name(i+1) ;
// ...
}
Would it not be possible to apply the names to their separate variables as well? I stored each name in it's own variable because later I need to apply a random number to each one so that each player can be assigned a random character to play from an array. If you need to see what I have in order to help out, just let me know.