C++ 随机生成的字典单词将仅显示以 B 开头的单词

C++ Randomly generated dictionary words will only show words starting with B

本文关键字:单词 显示 开头 随机 字典 C++      更新时间:2023-10-16

我正在为一个应该从字典中获取随机单词的应用程序编写代码。 我编写了这段代码,从包含字典中 84,000 个英语单词的文本文件中随机选择一行,但每次它生成一个新单词时,它似乎只显示以 B 开头的单词。有没有人可能知道导致此问题的原因?我希望它每次都是完全随机的,就像一次程序运行时它是一个 L 字,第二次运行时它是一个 C 字。这是代码:

#include "stdafx.h"
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <vector>
#include <string>
#include <fstream>
#include <cstdlib>
#include <random>
using namespace std;

int main()
{
srand(time(NULL));
vector<string> words;
ifstream file("words.txt");
string line;
while (getline(file, line)) words.push_back(line);
cout << words[rand() % words.size()] << endl;
system("pause");
return 0;
}

rand的常见实现(包括来自 Microsoft 的实现(仅返回 0 - 32767 范围内的数字。 您需要比这更大的范围。 它也不是一个非常好的随机数来源。

您需要使用<random>标头中提供的较新功能。 有关示例,请参阅此问题。

除了关于各种平台上rand()限制的其他答案之外,如果你想使用随机数生成器,你通常需要为它提供一个种子。为rand提供种子的方法是使用srand函数。种子通常只需要是每次程序运行时都不相同的值。通常人们会使用当前时间或类似时间,但从/dev/random 或您的平台的等效值中读取一些字节也很常见。这些都没有特别好的随机性,但总比没有好。尝试在第一次调用rand之前添加类似srand(time(0));的内容。它只需要执行一次,而不是每次调用rand一次。

如果你需要真正的随机性并且可以使用现代 c++,你可能想要通读 https://en.cppreference.com/w/cpp/numeric/random,特别是 std::uniform_int_distribution。

您想要的代码非常类似于:

std::random_device r;
std::default_random_engine engine(r());
std::uniform_int_distribution<int> dist(0, words.size() -1);
std::cout << words[dist()] << std::endl;

虽然你可以玩不同的引擎等。人们建议的一个常见的随机引擎是std::mt19937.