如何在c++中随机获取字符串

How to get a string randomly in c++

本文关键字:随机 获取 字符串 c++      更新时间:2023-10-16

我正在编写一个程序,每次运行该程序时,都会显示一个随机的引号。这应该通过使用randsrand来完成。我在做逻辑和搜索,但不明白怎么做。谁能告诉我出什么事了?

    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