If I were to ask the user to enter the number of employee. Could I put that user entered number into an array? If so how?

for example

int num;
cout << "enter number of employees: " ;
cin >> num;

array[num];

this code doesn't actually work because I already tried it and it gives me an error. Any help would be great. Thanks

Recommended Answers

All 2 Replies

You want a user to enter the number of employees and an array with that number of elements? That should be easy enough.
There are a number of options. You could use traditional dynamic memory allocation or alternatively a container class like vector. I'm going to assume you've not learnt the latter so you know anything about dynamic memory allocation (new/delete)? If the size of an array is not determinable when writing the program you can use new to allocate memory. The only thing is (unless you're using a pointer class like auto_ptr or something), you're going to have to delete the memory at the end of your program:

int *employee_numbers;
int num_employees;

std::cout<< "How many employees? ";
std::cin >> num_employees;

employee_numbers = new int[num_employees];

// fill the array

delete [] employee_numbers;

Or did I completely misinterpret your question?
>> Could I put that user entered number into an array? If so how?
I think I might have.

int nums[5];
int num;
std::cout<< "Enter num: ";
std::cin >> num;

nums[0] = num;
nums[1] = 42;
// etc

std::cout<< nums[0];

twomers yet again you have helped me.


Thanks alot!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.