c++ - 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;
}
}
}
解决方案
恕我直言,您需要使文本行的长度都相同,或者使用文件位置的数据库(表)。
使用文件位置
至少,创建一个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;
上述技术最大限度地减少了从文件中读取的量。
推荐阅读
- spring-webflux - 在 Spring WebFlux 中安排任务以更新数据库中的记录
- three.js - Three.js:如何将多个索引和向量数组合并为一个
- c# - 按钮提交在 ASP.NET MVC 中没有响应模式
- flutter - “对象?”类型的值 不能分配给“int”类型的变量
- php - 在codeigniter中加入3个表并显示数据
- r - 生成矩阵满足条件得到N个矩阵,并将N个接受的矩阵rbind在一起
- r - 如何在 ggplot2 中将 Y 轴上的标签隔开?
- header - Postfix header_checks 规则拒绝部分字符串?
- reactjs - Tizen Web 应用程序 - 嵌入
- arrays - creating sub section in vuejs not working