C:从文本文件中读取随机行

新手上路,请多包涵

我正在尝试编写一个程序,该程序从文本文件(包含 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;
    }

}

我可以让它像上面那样打印一条随机线,但不能打印三条随机线。

原文由 user5991813 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 690
1 个回答

你应该做什么取决于你所说的“随机”到底是什么意思,你想要什么样的输出,以及你有什么作为输入。

例如,如果您想选择任意三个不同的行,并且您希望所有行都有相同的机会作为任何输出行出现,并且如果您知道行数,您可以执行以下操作:

   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;
  }

活生生的例子

(或者你可以将整个文件读入一个字符串向量,打乱该向量并直接选择前三个,而不是使用索引数组间接执行此操作。)

如果你想随机选择三行,并且希望行有机会被选择两次或三次,那么你可以做类似 KaiEn Suizai 的第二个例子。

另一种选择不依赖于知道行数:Reservoir sampling with algorithm R 。有了这个,您可以阅读文件,根据某个公式以概率选择您看到的行。最后你有你想要的行数并打印出来。 例子

原文由 bames53 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏