如何从外部文件中选择一个随机单词到类
how to pick a random word from external file to class?
#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>
中可用的较新的随机数工具,因为它们的质量高于srand
和rand
。
最后,这是储层采样的完美用例。储层采样背后的想法是,你有一组潜在的数据(例如,单词列表(,每个项目都有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。
相关文章:
- 使用std::mt19937从字符串中返回一个随机单词
- 如何生成一个随机的 n 位数,其中 n 是任意的
- 当我尝试使用它时,Scanf 会抛出一个随机异常(scanf_s 也是如此)
- 我将如何在 cpp 中生成一个随机且独特的标题
- 从C++数组中选择一个随机元素
- 如何更改此notify_one以便它选择一个随机线程
- C++ 在运行时选择一个随机对象
- C++ 制作一个随机数字/字母生成器,代码中有问题
- 将一个随机的字符序列和int序列解析为单独的向量
- C 从向量的子集返回一个随机值
- 如何创建一个随机访问式的Rreference以访问.RC文件中定义的资源
- 在C 11中生成一个随机字符串
- 创建一个随机的std ::向量,其中一个和零C
- C/C++ - 生成一个随机字符串会覆盖以前的字符串(请参阅下面的代码)
- 需要在指定范围内生成一个随机整数
- 生成一个随机种子给srand()-不是时间(NULL)
- 选择一个随机方块并生成一个随机数
- 是否有一个随机函数可以生成 0 到 1 之间的数字
- 随机坐标和禁用下一个随机集的移动
- 如何在QtCreator(Linux Ubuntu)中编译和运行一个随机的单个C++文件