Pacific-Design.com

    
Home Index

1. Cpp 11

2. Read Random Line

Cpp 11 / Read Random Line /

Read Randon Line from a File

/*
 * g++ random_file.cc -std=c++11 && ./a.out
 * g++ random_file.cc -std=c++11 && ./a.out < random_file.cc
 * */
#include <cstdlib>
#include <iostream>
#include <random>
#include <string>
#include <fstream>

int main() {
    std::random_device seed;
    std::mt19937 prng(seed());
    std::string line, result;

    std::ifstream file("/home/air/links/keywords_health.dat");

    //for(std::size_t n = 0; std::getline(std::cin, line); n++) {
    for(std::size_t n = 0; std::getline(file, line); n++) {

        std::uniform_int_distribution<> dist(0, n);
        if (dist(prng) < 1)
            result = line;
    }

    std::cout << "random line: '" << result << "'\n";
}