如何从外部文件中选择一个随机单词到类

how to pick a random word from external file to class?

本文关键字:一个 随机 单词 从外部 文件 选择      更新时间:2024-05-09
#include <iostream>
#include <string>//needed to make string array
#include <fstream>//Needed for redaing in from external file
#include <cstdlib>//needed for rand() function (for random word)
#include <ctime>//needed for time() funtion to seed rand()
using namespace std;
/* Sage Balcita
April 25,2020
This program will take read in a random word from an external file and use it for a game of hang man */

//class
class Hangman{
public:
Hangman();//default constuctor
void setWord(string);
string getWord();
private:
string secretWord;

};
void Hangman::setWord(string Word)
{
ifstream inFile("randwords.txt");
if(inFile.is_open())
{
string wordlist[10];
for(int i = 0; i < 10; ++i)
{
inFile >> wordlist[i];

}
srand(time(0));
string secretword = wordlist[rand() % 10];
cout<< secretword << endl;
inFile.close();
}
}


//void wordPick();
int main()
{

//wordPick();
return 0;
}

/*void wordPick()//reads in external file and puts it in an array for a library of words to randomly choose
{

ifstream inFile("randwords.txt");
if(inFile.is_open())
{
string wordlist[10];
for(int i = 0; i < 10; ++i)
{
inFile >> wordlist[i];

}
srand(time(0));
string secretword = wordlist[rand() % 10];
cout<< secretword << endl;
inFile.close();
}
}
*/

所以我想做的是制作一个使用类进行操作的刽子手游戏。我的问题是,我一辈子都无法理解如何使我所做的从外部文件中读取随机单词的函数在类中工作。我专门为此制作了一个单独的函数,它本身就可以工作,但我不能让一个类为同一件事工作。

您的问题是,成员函数中的secretword变量与secretWord成员变量不同,这意味着您没有更新实例中的变量。如果您没有声明局部变量,您的代码就不会编译,因为在C++中大小写很重要。

但是,您的代码中还有其他一些质量问题。首先,您希望使用<random>中可用的较新的随机数工具,因为它们的质量高于srandrand

最后,这是储层采样的完美用例。储层采样背后的想法是,你有一组潜在的数据(例如,单词列表(,每个项目都有capacity/set_size的机会被包括在结果中(这只是capacity为1的特殊情况(。这也意味着你不需要在程序中存储每一个可能的单词,除非你想对游戏进行多次迭代,并且不想再次阅读单词列表(可能是个好主意(。

游戏的一个简单的储层采样实现如下所示:

std::string get_word(std::default_random_engine &engine) {
std::ifstream input_file{"words.txt"};
auto count = 0;
std::string read_word;
std::string result;
while(input_file >> read_word) {
std::uniform_int_distribution<int> dist{0, count};
auto const random_index = dist(engine);
if(random_index == count) {
result = read_word;
}
++count;
}
return result;
}

循环的每次迭代,都会读取一个单词,并生成一个0到count之间的随机数。如果随机数等于我们当前的计数,那么我们将替换当前选择的单词,否则我们什么也不做。

在第一次迭代中,随机数将始终为0,因此我们选择它。在第二次迭代中,我们有1/2的机会替换所选单词。在第三次迭代中,1/3,依此类推。每次迭代替换单词的几率都会降低,但任何给定单词被选中的几率都是1/N。