从文本文件中选择随机行

时间:2019-11-08 23:52:44

标签: c++

我需要编写一个8球代码,其中要显示11个选项,并且需要从文本文件中提取代码。我有它从文本文件中提取行,但是有时它没有任何写就有一个空行。而且我只需要一条有文字的行就可以了。 这是它需要借鉴的选项: 当然是! 毫无疑问,是的。 你可以指望它。 当然可以!稍后再问我。 我不确定。 我现在不能告诉你。 午睡后我会告诉你的。 没办法!我不这么认为。 毫无疑问,不会。 答案显然不是。

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

}

}

1 个答案:

答案 0 :(得分:0)

恕我直言,您需要使文本行的长度都相同,或者使用文件位置的数据库(表)。

使用文件位置

至少创建一个std::vector<pos_type>
接下来,从文件中读取各行,记录该字符串开头的文件位置:

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

要从文件中读取一行,请从数据库中获取文件位置,然后查找。

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

表达式text_line_positions.size()将返回文件中文本行的数量。

如果文件适合存储在内存中

如果文件适合存储在内存中,则可以使用std::vector<string>

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

要从文件中打印10行:

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

以上技术可最大程度地减少文件读取量。

相关问题