944,124 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 834
  • C++ RSS
Jun 6th, 2007
0

loop that creates strings?

Expand Post »
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...):
C++ Syntax (Toggle Plain Text)
  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?
Similar Threads
Reputation Points: 10
Solved Threads: 7
Unverified User
Matt Tacular is offline Offline
187 posts
since Jun 2006
Jun 6th, 2007
0

Re: loop that creates strings?

you will want to create an array, or vector, of strings.
C++ Syntax (Toggle Plain Text)
  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
C++ Syntax (Toggle Plain Text)
  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.
Sponsor
Team Colleague
Featured Poster
Reputation Points: 5608
Solved Threads: 2283
Retired and Enjoying Life
Ancient Dragon is offline Offline
21,961 posts
since Aug 2005

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: problem dealing with constructor
Next Thread in C++ Forum Timeline: noob question, answer probably pretty easy, i just don't know where to start





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC