例如,我有带有单词列表的 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();
}