loop that creates strings?

Please support our C++ advertiser: Programming Forums - DaniWeb Sister Site
Reply

Join Date: Jun 2006
Posts: 187
Reputation: Matt Tacular is an unknown quantity at this point 
Solved Threads: 7
Matt Tacular's Avatar
Matt Tacular Matt Tacular is offline Offline
Unverified User

loop that creates strings?

 
0
  #1
Jun 6th, 2007
Is there a way to make a loop that creates strings? I ask the user how many players there are, and then the loop makes that many strings in order to get all of their names... Something like this, (but not in normal english...):
  1. cout << "How many players? " << endl;
  2. cin >> numOfPlayers;
  3.  
  4. for(unsigned int i=0 ; i<numOfPlayers ; i++)
  5. {
  6. /* create new string */
  7. }
And then, if that's possible, how could I access each one individually?
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 15,662
Reputation: Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute Ancient Dragon has a reputation beyond repute 
Solved Threads: 1502
Team Colleague
Featured Poster
Ancient Dragon's Avatar
Ancient Dragon Ancient Dragon is offline Offline
Still Learning

Re: loop that creates strings?

 
0
  #2
Jun 6th, 2007
you will want to create an array, or vector, of strings.
  1. vector<string> names;
  2. <snip>
  3. for(unsigned int i=0 ; i<numOfPlayers ; i++)
  4. {
  5. string name;
  6. cout << "Enter name #" << i << "\n";
  7. getline(name, cin);
  8. names.push_back(name);
  9. }

>>how could I access each one individually?
From the above vector: if n is an integer between 0 and the number of names in the array
  1. string thisName = names[n];

There is another way to access individual members of a vector - using an interator -- but its a little more complex.
Last edited by Ancient Dragon; Jun 6th, 2007 at 11:27 pm.
Don't PM me with questions -- you might get a nasty PM in response. If you have a question then post it in one of the forums.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:




Views: 719 | Replies: 1
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC