【问题标题】:How to randomly generate a string each iteration? [closed]如何在每次迭代中随机生成一个字符串? [关闭]
【发布时间】:2021-07-03 18:58:49
【问题描述】:

我想知道如何在每次迭代中随机生成一个字符串。我的代码当前每次迭代都会生成相同的字符串。如果我输入 3 次,那么它会给我 3 次相同的字符串。我每次都想要一个不同且随机生成的字符串

#include <iostream>
#include <string>
#include <cstdlib>     /* srand, rand */
#include <ctime>
using namespace std;

string RandomString(int len)
{
   string str = "0123456789ABCDEFabcdef";
   string newstr;
   int pos;
   while(newstr.size() != len) {
    pos = ((rand() % (str.size() - 1)));
    newstr += str.substr(pos,1);
   }
   return newstr;
}

int main()
{
   srand(time(NULL));
   string random_str = RandomString(32);
   int user_input;
   
   cout << "Enter how many codes you want: ";
   cin >> user_input;
   for (int i = 0; i < user_input; i++)
   {
   cout << "random_str : " << random_str << endl;
   }

}

Enter how many codes you want: 3 random_str : ae2e8D6C7C04Fb3b83Ec457bcedcC5F5 random_str : ae2e8D6C7C04Fb3b83Ec457bcedcC5F5 random_str : ae2e8D6C7C04Fb3b83Ec457bcedcC5F5

这是我当前的输出。请记住,它们每次都应该不同

【问题讨论】:

  • 你只调用一次RandomString()
  • 确实,您正在从main() 打印相同的字符串。您是否考虑过在main() 中的每个 循环迭代中调用RandomString()
  • 非常感谢你们纠正我的错误。你们做得很好并且提供了帮助。
  • @DarknessArise03 如果您更好奇,using the string fuzzer in this answer,此代码 here 可以满足您的需求,还有更多功能。如果你看一下它,它使用你的字符集,它使用你的最小和最大长度(32),它为 for 循环的每次迭代生成 1 个随机字符串。
  • 无关:std::shuffle 可以为您节省大量代码。

标签: c++ string function loops random


【解决方案1】:

您需要在每次迭代时调用该函数,将其放在 for 循环中:

int main()
{
    srand(time(NULL));

    int user_input;

    cout << "Enter how many codes you want: ";
    cin >> user_input;
    
    for (int i = 0; i < user_input; i++)
    {
        string random_str = RandomString(32); //<-- here
        cout << "random_str : " << random_str << endl;
    }
}

使用 C++ 你有更好的随机数引擎,看看这里:

https://en.cppreference.com/w/cpp/numeric/random

【讨论】:

    猜你喜欢
    • 2018-03-24
    • 2022-07-08
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多