I have a .dat file with 10 lines, each line has a word. How would I randomly select a line so I could bring the word from the line into my function?
Asked
Active
Viewed 619 times
1 Answers
0
Here ya go. You can change the file name to whatever, and change the number of lines if you need. Based on the info you gave, I made this.
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <ctime>
int main()
{
const char* myFileName = "data.txt";
const int numberOfLines = 10;
std::ifstream myData;
std::string lines[numberOfLines];
int index = 0;
myData.open(myFileName, std::ifstream::in);
while (myData.good() && index < numberOfLines ) {
myData >> lines[index];
index++;
}
myData.close();
srand(time(NULL)); // Seed random number generator
int randomIndex = rand() % index; // Incase there were less than numberOfLines
std::cout << lines[randomIndex] << std::endl;
return 0;
}