C++ 随机生成的字典单词将仅显示以 B 开头的单词
C++ Randomly generated dictionary words will only show words starting with B
我正在为一个应该从字典中获取随机单词的应用程序编写代码。 我编写了这段代码,从包含字典中 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
.
相关文章:
- 以C++显示单词的所有前缀
- 显示文件中具有最小给定元音数的单词
- C++ 随机生成的字典单词将仅显示以 B 开头的单词
- 使用 c++ MuPDF 突出显示 PDF 中的一些单词
- 如何在C++中突出显示整个单词?
- 尝试创建一个读取.txt文件,显示它,计数唯一单词的程序,并在使用了多少次的情况下显示独特的单词.C
- 对于文件中的每个不同单词,显示该单词在文件中出现的次数
- 我如何修改我的C 程序以显示用户输入的单词,并使用堆栈向后
- 在C/C 中显示来自TXT文件的单词
- 如何检查文本文件中每个单词的出现次数并显示C++次数
- Check Writer:使程序将值10-19显示为单词
- C++,计算字符串中的重复单词并显示
- 有没有一个网站可以生成所有可能的显示单词的方式
- 当键入指定单词作为第一个字母时显示输出,并忽略后面的其他单词
- 突出显示qtextedit中x和y作为位置的单词
- 在c++中显示一行vs单词
- 如何使用c++在没有读线的情况下显示字符串中的多个单词
- 从文本文件中查找一个单词,然后使用c++显示该单词所在的行号
- 我如何写一个Qt正则表达式来突出显示字符串开始和结束与非单词字符
- visual studio 2010 - c++显示有组织的单词列表