I am trying to code a program that picks 3 random lines from a text file (that contains 50 lines) and outputs them to the screen.
Here is my current code:
string line;
int random = 0;
int numOfLines = 0;
ifstream File("file.txt");
srand(time(0));
random = rand() % 50;
while(getline(File, line))
{
++numOfLines;
if(numOfLines == random)
{
cout << line;
}
}
I can get it to print one random line like it does above but not three random lines.
What you should do depends on what exactly you mean by 'random' and what kind of output you want, and what you have as input.
For example, if you want to select any three different lines, and you want all lines to have an equal chance to appear as any of the output lines, and if you know the number of lines you can do something like this:
int number_of_lines = 50;
// a vector to hold all the indices: 0 to number_of_lines
std::vector<int> line_indices(number_of_lines);
std::iota(begin(line_indices), end(line_indices), 0); // init line_indices
// C++11 random library (should be preferred over rand()/srand())
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
std::mt19937 eng(seed);
// shuffle the line_indices:
std::shuffle(begin(line_indices), end(line_indices), eng);
int number_of_lines_to_select = 3;
assert(number_of_lines_to_select <= number_of_lines);
std::string line;
std::ifstream file("file.txt");
int line_number = 0;
while (std::getline(file, line)) {
for (int i = 0; i < number_of_lines_to_select; ++i) {
if (line_number == line_indices[i]) {
std::cout << line << '\n';
}
}
++line_number;
}
Live example
(Or you could just read the whole file into a vector of strings, shuffle that vector and pick the first three directly, instead of doing this indirectly using an array of indices.)
If you want to select three random lines and you want lines to have chance of being selected twice or three times, then you can do something like KaiEn Suizai's second example.
Another option doesn't depend on knowing the number of lines: Reservoir sampling with algorithm R. With this you read through the file, picking lines as you see them with a probability according to a certain formula. At the end you have the number of lines you want and you print them out. Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With