C++ : Read random line from text file

时光毁灭记忆、已成空白 提交于 2021-02-16 18:58:34

问题


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.


回答1:


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




回答2:


You need to get a new random number after you get one. This method will need 3 times loop on the file.

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

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

OR you get three random number then just start while loop

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

    if(numOfLines == random || numOFLines == random1 || numOfLines == random2)
    {
        cout << line;
    }
}



回答3:


#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();
    }

}



回答4:


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


来源:https://stackoverflow.com/questions/36168615/c-read-random-line-from-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!