0

I have a pretty simple question. I have a program that prompts the user for how many people are desired for a simulation within the program. I am wondering how I would go about initializing the value of the cin objects. Here is a snippet of what I'm looking at:

cout<<"Number of users? ";
int users;
cin>>users;

The basics^. I want to take the input I get for users and make this many people objects. I have a class called CPerson that has several basic member functions like getName() and getGender(). I'm not so concerned with these. I then need to be able to put the number of users created into a queue which I figure won't be so hard once I have the objects initialized.

Thank you for any help.

UPDATE: I ended up with something that looked like this which yielded desired results. Thanks to all.

vector<CPerson*> people;
for (unsigned int x=0; x<users; x++) {
    CPerson *user = new CPerson(Names[x]);
    people.push_back(user);
    cout<<user->getName()<<endl;
}
5
  • Look into the standard libraries options for storage containers, you may benefit most from std::vector. Commented Nov 17, 2013 at 20:26
  • @izuriel I am trying to implement a vector but the compiler throws an exception about the vector subscript being out of range. vector<CPerson*> user; for (unsigned int x=0; x<numUsers; x++) { CPerson *people; people = user[x]; } Commented Nov 17, 2013 at 20:48
  • @zweed4u That's definitely wrong. What is that code doing? Commented Nov 17, 2013 at 20:54
  • Just for you to know, this code leaks memory... Commented Nov 18, 2013 at 19:43
  • @HenriqueBarcelos thanks for the heads up. No worries though. I checked for memory leaks and had the logic in my main file. =) Commented Nov 18, 2013 at 20:36

1 Answer 1

1

Once you get the input from the user you can then create a dynamic array:

int n;
std::cin >> n;

int* array = new int[n];
// ...
delete[] array;

Or you can use std::vector where the size can accommodate the users input.

Sign up to request clarification or add additional context in comments.

2 Comments

I thought array sizes in C++ had to be compile time constants? Or is this a relatively new feature of C++?
@izuriel This is true only when you are creating an array on the stack (the size must be known at compile time). Since we are allocating on the heap, and the size is known at runtime, this works fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.