1

I wrote a sentinel-controlled C++ program in which you have to input a set of names. There is no limit to how many names you can input. When you are done inputting the names, you just type "1" to quit. Here is my code:

#include <iostream>
#include <string>

using namespace std;

int main()
{
    string name;
    int nofPeople = 0;
    cout<<"Enter a name or 1 to quit:\n";
    cin>>name;
    while(name != "1")
    {
        nofPeople = nofPeople + 1;

        cout<<"Enter another name or 1 to quit:\n";
        cin>>name;
    }
}

Now I want to create an array with length that equals 'nofPeople' and I want the elements of that array to be the names that I already entered. How do I do that?

droman07
  • 127
  • 1
  • 8

2 Answers2

1

You may use the std::vector and its push_back method to add the names to the vector as they come in by the user.

hamid attar
  • 388
  • 1
  • 8
0

The standard way of doing this is by creating an std::vector<std::string> into which you will be adding strings as you receive them, and in the end, (once you have collected all strings,) converting the vector to an array.

However, unless there is some other weird requirement which you have not mentioned, I would strongly recommend that you forget about using an array and continue working with the vector throughout your program.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
  • I am pretty new to C++ programming so I'm not familiar with std::vector. Could you show me an example of how I could use it? Thank you. – droman07 Feb 10 '15 at 10:22