Random name selection

I have a list of 1000+ names in a text file and would like it to select names at random.
It does not matter if it repeats, and chances are it will not anyways since I will only be selecting 10-20.

Any help to get me started?
would like it to select names at randomIt?

The most straight forward method is to read the names into a vector.

srand() seeds the random number generator.
rand() returns a number in the range 0 - RAND_MAX.

So suppose you have read 1234 names into your vector, and your vector of names is names, this selects a random name.
1
2
size_t idx = rand() % (RAND_MAX + 1); // random selection
std::string name = names[idx];
I apologize for pretty much DOING it for you, but this could be a rather valuable learning experience for you; below is the code to what you want to do... It has not been tested, nor even really looked at. I made this in about five minutes.






try something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <time.h>

using namespace std;

int main() {
ifstream myFile;
myFile.open("names.txt");
string names[1000]; // holds the 1000 names in the file.
string randomNames[20];// holds the randomly generated names FROM the file.
int a = 0;
int randNum;
while (myFile.good()){
getline(myFile, names[a]); // reads the names from the text file, into an array named "names[]."
a++;
}
for (int i = 0; i < 20; i++) { // makes this program iterate 20 times; giving you 20 random names.
srand( time(NULL) ); // seed for the random number generator.
randNum = rand() % 1000 + 1; // gets a random number between 1, and 1000.
randomNames[i] = names[randNum]; 
}
for (int i = 0; i < 20; i++) {
cout << randomNames[i] << endl; // outputs all 20 names at once.
}
myFile.close();
system("pause");
}






Topic archived. No new replies allowed.