c++ - 如何在txt文件(c ++ ifstream)中获取随机字符串?
问题描述
例如,我有带有单词列表的 txt db(在屏幕中),我需要在ifstream
C++ 中的这个文件中输出随机 3 行。我在for
循环中尝试过,但它非常消耗
#include "gamewindow.h"
#include "ui_gamewindow.h"
#include <iostream>
#include <fstream>
#include <string>
#include <QLabel>
#include <ctime>
using namespace std;
string login;
bool start_is_clicked=false;
GameWindow::GameWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::GameWindow)
{
ui->setupUi(this);
ifstream logined("last_login.txt");
getline(logined,login);
QString qstring_login = QString::fromLocal8Bit(login.c_str());
ui->login_label->setText(qstring_login);
logined.close();
}
GameWindow::~GameWindow()
{
delete ui;
}
int countStringsWords(){
string current;
int count = 0;
ifstream words("word_db.txt");
do{
getline(words,current);
count++;
}while(!words.eof());
words.close();
return count;
}
void getLabelText(){
srand(time(NULL));
ifstream words("word_db.txt");
int start=rand()%countStringsWords();
words.close();
cout<<start<<endl;
}
void GameWindow::on_Start_stop_clicked()
{
if(ui->Start_stop->text()=="START"){
ui->Start_stop->setText("STOP");
getLabelText();
}
else if(ui->Start_stop->text()=="STOP"){
ui->Start_stop->setText("START");
}
else{
cout<<"Button error"<<endl;
}
}
工作区域:
int countStringsWords(){
string current;
int count = 0;
ifstream words("word_db.txt");
do{
getline(words,current);
count++;
}while(!words.eof());
words.close();
return count;
}
void getLabelText(){
srand(time(NULL));
ifstream words("word_db.txt");
int start=rand()%countStringsWords();
words.close();
}
解决方案
升级您当前的解决方案:
您可以做的是使用动态列表(向量)用文件填充向量,然后生成 3 个随机索引并返回这三个随机字符串的数组。如果文本文件的长度为 n,这将是 O(n) 空间和时间复杂度。
有更好的解决方案吗?
如果您想要 O(1) 时间和空间复杂度(不考虑设备上的文件存储),那么我建议您将文件设为 XML 文件,因为这将允许您在任何索引处本地访问文件,这意味着您不需要将整个文件加载到一个数组中,对于较大的文件不建议这样做。
int * ReturnRandomWords(){
string current;
vector<std::string> WordsFromFile
ifstream words("word_db.txt");
do{
getline(words,current);
WordsFromFile.push(current);
}while(!words.eof());
words.close();
string v1 = WordsFromFile.at( rand() % WordsFromFile.size());
string v2 = WordsFromFile.at( rand() % WordsFromFile.size());
string v3 = WordsFromFile.at( rand() % WordsFromFile.size()));
string arr [3] = {v1, v2, v3};
return arr;
}
推荐阅读
- angular - Form validation with variable input list in Angular?
- c++ - Why does the string version of this template function compile but the float version doesn't?
- java - How to pass spinner value to the target language in IBM api?
- google-apps-script - 如何使用脚本编辑器将分节符添加到谷歌文档
- algorithm - 在字符串中查找短语的更有效方法?
- css - Material-UI style buttons on the right
- ios - Account of the cloud used by CloudKit
- docker - docker-compose 在构建过程中无法连接到容器
- python - cef加载URL时禁用任务栏图标闪烁
- python - 如何通过python脚本在可执行文件中执行命令