簡體   English   中英

C ++:從文本文件讀取隨機行

[英]C++ : Read random line from text file

我正在嘗試編寫一個程序,該程序從文本文件(包含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;
  }

現場例子

(或者,您可以將整個文件讀入一個字符串向量中,將其向量改組並直接選擇前三個向量,而不是使用索引數組來間接執行此操作。)

如果要選擇三條隨機線,並且希望線有兩次或三次被選中的機會,則可以執行類似KaiEn Suizai的第二個示例。

另一個選擇不依賴於知道行數:使用算法R進行儲層采樣。 通過此操作,您可以通讀文件,並根據特定公式以幾率選擇看到的行。 最后,您具有所需的行數,然后將其打印出來。

獲得一個隨機數后,您需要獲取一個新的隨機數。 此方法將需要在文件上循環3次。

int count = 1;
While(count <= 3)
{
    random = rand() % 50;
    while(getline(File, line))
    {
        ++numOfLines;

        if(numOfLines == random)
        {
            cout << line;
        }
    }
    count++;
}

或您獲得三個隨機數,然后在while循環中開始

random = rand() % 50;
random1 = rand() % 50;
random2 = rand() % 50;
while(getline(File, line))
{
    ++numOfLines;

    if(numOfLines == random || numOFLines == random1 || numOfLines == random2)
    {
        cout << line;
    }
}
#include <iostream>
#include <fstream>
#include <random>
#include <string>
#include <vector>

int randomNumber() { // Using C++11 random features
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_real_distribution<double> dist(0.0, 50.0);
    return dist(mt);
}

int main()
{
    std::ifstream file("file.txt");
    std::vector<std::string> lines(50); // # of lines here (instead of using push_back)

    while (file.is_open()) {
        for (auto i = 0; i < lines.size(); ++i) {
            std::getline(file, lines[i]);
        }
        file.close();
    }

    std::vector<int> rand_index(3); // # of random numbers here

    for (auto i = 0; i < rand_index.size(); ++i) {
        rand_index[i] = randomNumber();
    }

}
//first store the line numbers you want to read in array, you can do it as follow:

int linetoRead[3];

for(int i =0 ;i<3;i++)
{
    linetoRead[i] =  rand() % 50;
}

bool isKeep(int lineN)
{
    for(int i =0 ;i<3;i++)
    {
    if(linetoRead[i] == lineN)
        return true;
    }
    return false;
}
//then do the while loop as follows
int LineRead = 0;
int lineN = 0;
while(getline(File, line) && LineRead < 3)
{
    if(isKeep(lineN))
    {
        // keep the line or display it
        LineRead++;
        cout << line;
    }
    lineN++;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM