-1

I need to load the info from the vector into the array, does anyone know how I might be able to do that?

What I am making is something where you can input data onto a text file, than have it pull (number) random items from the list.

I appreciate any help you can provide to me completing this task.

Eric Lang
  • 274
  • 1
  • 2
  • 16
  • Why do you need to do that. Also, [`while (!eof())` is wrong.](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – chris Jul 12 '13 at 18:07
  • It would be nice if you format the code use `int main()` inseatd of `tmain` (which is not standard) and remove not needed headers (like 'stdafx.h', 'Windows.h', ...) – Jan Herrmann Jul 12 '13 at 18:22

1 Answers1

3

Try something like this:

#include <random>
...
srand( time(NULL) );        // Initializes the random seed
string randFromVector;
randFromVector = vlist[ rand() % vlist.size() ];    // Takes the data at this address

rand() provides a random number ("psuedo" random, technically). Then, we use modular on the length of the vlist to make sure it references a legal address.

edit: You only need to initialize the random seed once. Every time you call rand() it will return a different number.

You could also remove the modulus bias by doing this:

int x;
do {
    x= rand();
} while ( x >= vlist.size() );

randFromVector = vlist[ x];
Community
  • 1
  • 1
Daniel T
  • 88
  • 11
  • Well, `rand()` doesn't necessarily return a *different* number every time, but it will get another "random" number. Because it's random, it could be the same, though it's not likely – wlyles Jul 12 '13 at 18:21
  • 1
    @wlyles Furthermore, rand() is technically a "preset" sequence of numbers based on the seed, IIRC. So if someone else somehow got the same seed as you, their "random" numbers would be identical to yours. – Daniel T Jul 12 '13 at 18:24
  • @chris How would I avoid using modulus in this example? – Daniel T Jul 12 '13 at 18:24