c++ - 如何在每次迭代中随机生成一个字符串?

标签 c++ string function loops random

我想知道如何在每次迭代中随机生成一个字符串。我的代码当前每次迭代都会生成相同的字符串。如果我输入 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

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

最佳答案

您需要在每次迭代时调用该函数,并将其放在 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

关于c++ - 如何在每次迭代中随机生成一个字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66994965/

相关文章:

c++ - 我的算法只将第一个字写入文件?

c++ - 为什么 STL 使用/不使用分配器参数重载其构造函数?

string - oracle中如何将csv转换为表格

c++ - 没有匹配的函数要调用:错误:必须使用 ‘.*’或 ‘->*’来调用 ‘f (…)’中的指针成员函数,例如 ‘(… ->* f) (…)’

Python-将变量参数传递给 subprocess.call 的最佳方式

c++ - Visual Studio 交叉编译到 Linux

c++ - boost 的托管内存中的内存对齐约束

arrays - 如何将字符数组传递给字符串

swift - String.endIndex递增错误

python - 如何不将函数用作其他函数的参数