mardi 22 mars 2016

C++ : Read random line from text file

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.




Aucun commentaire:

Enregistrer un commentaire