如何在c++中随机获取字符串
How to get a string randomly in c++
我正在编写一个程序,每次运行该程序时,都会显示一个随机的引号。这应该通过使用rand
和srand
来完成。我在做逻辑和搜索,但不明白怎么做。谁能告诉我出什么事了?
const string Quot[14] = { "1)Love Pakistan", "2)Be Honest", "3)Work Work and Work", "4)I am always doing things I cannot do.That is how I get to do them.", "5)It is not what we take up, but what we give up, that makes us rich.", "6)You can do anything, but not everything.", "7)Thinking will not overcome fear but action will. ", "8)We read the world wrong and say that it deceives us.", "9)You miss 100 percent of the shots you never take.", "10)He is the happiest, be he king or peasant, who finds peace in his home.", "11)Your work is to discover your work and then, with all your heart, to give yourself to it.", "12)In order to be effective truth must penetrate like an arrow – and that is likely to hurt", "13)You must be the change you wish to see in the world", "14)Humans are satisfied with whatever looks good; ? Heaven probes for what is good." };
for (int i = 0; i < 14; i++)
{
int choiceLen[i] = c.getLenght(Quot[i]);
const int randomLength = 1;
string randomStr[randomLength + 1];
for (int i = 0; i < randomLength; i++)
{
randomStr[i] = Quot[i][rand() % choiceLen[i]];
cout << randomStr[i] << endl;
}
}
rand
是一个伪随机数生成器。这意味着它不是真正的随机,第一个限制之一是-基于可测试性的遗留原因-它总是从相同的种子开始,因此总是产生相同的随机序列。
为了打破这个,你需要提供一些熵,一个随机种子。最常见的方法是在main()的开头执行以下操作:
srand(time(nullptr));
警告:如果你在同一秒内运行两次,它将得到相同的随机种子。
如果你有c++ 11,你可以使用<random>
和std::shuffle
#include <iostream>
#include <string>
#include <array>
#include <random>
#include <algorithm>
int main()
{
std::array<std::string, 3> quotes = {
"1 hello", "2 world", "3 hello world"
};
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> quoteSeed(0, quotes.size() - 1);
int quoteNo = quoteSeed(gen);
auto quote = quotes[quoteNo];
std::shuffle(quote.begin(), quote.end(), gen);
std::cout << quote << "n";
}
实时演示:http://ideone.com/Lv1M7w
相关文章:
- 为什么我的 2d 数组的第二行从 RAM 中获取随机值?
- 如何在 C++ 中获取随机函数的周期性
- C 编程:在循环时运行 2 并从 loop1 获取数据的随机结果
- 有什么方法可以从C 中的Enum类获取随机
- 从容器中获取随机元素,该容器在恒定时间内没有严格的元素顺序
- 在新数组中获取随机值
- 从满足谓词的迭代器中均匀随机的容器中获取迭代器
- 根据值的概率从 Map 获取随机键
- 试图从文件中获取随机数字的总和
- 无法获取随机字符串
- 如何从向量中获取随机和唯一值?
- 获取C++中的随机唯一整数
- Qhash-热以获取随机键和价值
- 如何从指针列表中获取随机指针
- 从集合中随机给定整数 0、1 和 2 时获取整数 0、1 和 2 的快速方法
- 获取用于 TCP 连接的随机端口
- c ++中是否有任何方法可以在随机访问的列表中获取元素
- 获取随机科学数字而不是输入
- 如何在c++中从文件中随机获取信息
- 如何在c++中随机获取字符串