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.
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.
#include <windows.h>
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
#include <time.h>
usingnamespace 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");
}