I stored a long list of names from a .txt file into a vector called BunnyNames, and I am trying to find a way to randomly generate elements (names) from within said vector. So far all it's doing is printing the names consecutively from the .txt file instead of randomly like I want. Here is my code:
int main()
{
using namespace std;
string name;
vector<string> BunnyNames;
ifstream myfile("names.txt");
if(!myfile)
{
cerr <<"Error opening output file"<< endl;
system("pause");
return -1;
}
while (getline(myfile, name))
{
BunnyNames.push_back(name);
}
srand (time(0));
int randomIndex = rand() % BunnyNames.size();
std::cout<<BunnyNames[randomIndex]<<std::endl;
return 0;
}
I only want it to print one name at a time, but I want that one name to be random.
Here are the first few lines of the file:
Abracadabra
Ace
Akeeta
Considering that you want to randomly access vector elements, this might be because you are setting the seed inside the loop.
Try seeding it only one at the beginning and use
rand() % BunnyNames.size()
inside the loop as:Another case might be that the loop is iterating fast enough that in successive iterations, the time doesn't change, thus generating same values.