我正在尝试编写一个程序,从文本文件(包含 50 行)中随机选取 3 行并将它们输出到屏幕。
这是我当前的代码:
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;
}
}
我可以让它像上面那样打印一个随机行,但不能打印三个随机行。
最佳答案
您应该做什么取决于“随机”的确切含义、您想要什么样的输出以及您拥有什么作为输入。
例如,如果你想选择任意三行不同的行,并且你希望所有行都有相同的机会出现为任何输出行,如果你知道行数,你可以这样做:
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;
}
(或者您可以将整个文件读入一个字符串 vector ,打乱该 vector 并直接选择前三个,而不是使用索引数组间接执行此操作。)
如果你想随机选择三行,并且你希望这些行有机会被选择两次或三次,那么你可以像 KaiEn Suizai 的第二个例子那样做。
另一个选项不依赖于知道行数:使用 algorithm R 进行水库采样.有了这个,您可以通读文件,根据特定公式以概率选择您看到的行。最后你有你想要的行数并打印出来。 Example
关于C++ : Read random line from text file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36168615/