943,954 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 524
  • C++ RSS
Nov 19th, 2007
0

Array Troubles

Expand Post »
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

C++ Syntax (Toggle Plain Text)
  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
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
cl3m0ns is offline Offline
30 posts
since Oct 2007
Nov 19th, 2007
0

Re: Array Troubles

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:

cpp Syntax (Toggle Plain Text)
  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.

cpp Syntax (Toggle Plain Text)
  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.
Reputation Points: 453
Solved Threads: 57
Posting Virtuoso
twomers is offline Offline
1,873 posts
since May 2007
Nov 19th, 2007
0

Re: Array Troubles

twomers yet again you have helped me.


Thanks alot!
Reputation Points: 10
Solved Threads: 0
Light Poster
cl3m0ns is offline Offline
30 posts
since Oct 2007

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: Remove newline character
Next Thread in C++ Forum Timeline: Looping error





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


Follow us on Twitter


© 2011 DaniWeb® LLC