Array Troubles

Please support our C++ advertiser: Intel Parallel Studio Home
Reply

Join Date: Oct 2007
Posts: 30
Reputation: cl3m0ns is an unknown quantity at this point 
Solved Threads: 0
cl3m0ns's Avatar
cl3m0ns cl3m0ns is offline Offline
Light Poster

Array Troubles

 
0
  #1
Nov 19th, 2007
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

  1. int num;
  2. cout << "enter number of employees: " ;
  3. cin >> num;
  4.  
  5. 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
Reply With Quote Quick reply to this message  
Join Date: May 2007
Posts: 1,871
Reputation: twomers has a spectacular aura about twomers has a spectacular aura about twomers has a spectacular aura about 
Solved Threads: 56
twomers's Avatar
twomers twomers is offline Offline
Posting Virtuoso

Re: Array Troubles

 
0
  #2
Nov 19th, 2007
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:

  1. int *employee_numbers;
  2. int num_employees;
  3.  
  4. std::cout<< "How many employees? ";
  5. std::cin >> num_employees;
  6.  
  7. employee_numbers = new int[num_employees];
  8.  
  9. // fill the array
  10.  
  11. 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.

  1. int nums[5];
  2. int num;
  3. std::cout<< "Enter num: ";
  4. std::cin >> num;
  5.  
  6. nums[0] = num;
  7. nums[1] = 42;
  8. // etc
  9.  
  10. std::cout<< nums[0];
Last edited by twomers; Nov 19th, 2007 at 6:31 pm.
I blag!?
"Mr Kitty, you have to live in the attic now. Here, write a diary."
I am the Walrus!
Reply With Quote Quick reply to this message  
Join Date: Oct 2007
Posts: 30
Reputation: cl3m0ns is an unknown quantity at this point 
Solved Threads: 0
cl3m0ns's Avatar
cl3m0ns cl3m0ns is offline Offline
Light Poster

Re: Array Troubles

 
0
  #3
Nov 19th, 2007
twomers yet again you have helped me.


Thanks alot!
Reply With Quote Quick reply to this message  
Reply

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



Similar Threads
Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC