【发布时间】: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