我想创建一个c++程序,它将在运行时生成一个用户指定长度(即最小值和最大值)的随机字符串

I want to create a c++ program that will generate a random string of user specified lenght (i.e min and max) at runtime

本文关键字:一个 最小值 字符串 随机 用户 最大值 运行时 程序 c++ 创建      更新时间:2024-04-28

目标是使用用户定义的函数创建它。这样的C++程序具有用户定义的功能(名称:GenerateRandomWords(,其功能是使用英文字母生成随机单词。将所有这些单词保存在文本文件(名称:Output.txt(以及字符串类型的数组中。作为一个安装程序,我面临的问题是它成功地生成了第一个单词并将其存储在字符串中,但当循环开始生成第二个单词时,程序会运行一段时间,然后结束。这是代码,提前感谢您的帮助:

#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum)-1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
int main()
{
int n = 0, a = 0;
cout << "Howe many strings you want to generatet";
cin >> n;
cout << "Lenght of each :t";
cin >> a;
string le;
string ar[] = { "" };
for (int i = 0; i < n; i++)
{
for (int j = 0; j < a; j++)
{
le += genRandom();
}
ar[i] = le;
le = "";
cout << ar[i] << endl;
}
cout << "Out of both loopn";
for (int i = 0; i < n; i++)
cout << ar[i] << endl;
}

在这一行:

string ar[] = { "" };

您正在创建一个大小为1的字符串数组。因此,当您尝试将第二个字符串添加到此数组中时,就会调用未定义的行为。如果你只使用vector<string>,你就不会有这个问题:

vector<string> ar;

在你正在做的线上:

ar[i] = le;

你应该这样做:

ar.push_back(le);

这是一个工作演示。

此外,你的"随机"选择也不是很随机。查看random标头,了解如何更好地做到这一点。

根据您的要求,您需要使用指定的字符阵列变量alphanum来获取每个字符串的长度和要打印的字符串数,并创建output.txt来保存它。

考虑以下代码:

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <fstream>
const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
void generate(int, int);
void setOutput(char[]);
main(void)
{
int length, strings;
std::cout << "How many strings & length (sep. by SPACE): ";
std::cin >> strings >> length;
srand(time(0));
generate(length, strings);
return 0;
}
void generate(int len, int str)
{
char array[len];
int max = sizeof(alphanum) / sizeof(alphanum[0]);
std::ofstream output("output.txt");
for (int k = 1; k <= str; k++)
{
for (int i = 0; i <= len; i++)
array[i] = alphanum[(rand() % max) + 1];
std::cout << array << std::endl;
output << array << std::endl;
}
}

输出

How many strings & length (sep. by SPACE): 5 5
5Xe*%%
xOD8TQ
YfrM*X
#j&L5&
U8*EYB

注意:首先,记住srand()会让随机值在每次执行程序时发生变化。其次,此程序将生成一个output.txt以满足您的标准。

尽情享受吧!