简体   繁体   中英

Picking a random line from a text file

I need to write an 8 ball code that has eleven options to display and it needs to pull from a text file. I have it taking lines from the text file but sometimes it takes an empty line with no writing. And I need it to only take a line that has writing. Here are that options it needs to draw from: Yes, of course, Without a doubt. yes. You can count on it. For sure.Ask me later. I'm not sure. I can't tell you right now. I'll tell you after my nap, No way.I don't think so. Without a doubt, no. The answer is clearly NO.

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

}

}

IMHO, you need to either make the text lines all the same length, or use a database (table) of file positions.

Using File Positions

Minimally, create a std::vector<pos_type> .
Next read the lines from the file, recording the file position of the beginning of the string:

std::vector<std::pos_type> text_line_positions;
std::string text;
std::pos_type file_position = 0;
while (std::getline(text_file, text)
{
    text_line_positions.push_back(file_position);

    // Read the start position of the next line.
    file_position = text_file.tellg();
}

To read a line from a file, get the file position from the database, then seek to it.

std::string text_line;
std::pos_type file_position = text_line_positions[5];
text_file.seekg(file_position);
std::getline(text_file, text_line);

The expression, text_line_positions.size() will return the number of text lines in the file.

If File Fits In Memory

If the file fits in memory, you could use std::vector<string> :

std::string text_line;
std::vector<string> database;
while (getline(text_file, text_line))
{
    database.push_back(text_line);
}

To print the 10 line from the file:

std::cout << "Line 10 from file: " << database[9] << std::endl;

The above techniques minimize the amount of reading from the file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM