所以现在我有了这段代码,它可以根据用户输入确定的设定增量生成随机字母。
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int sLength = 0;
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int stringLength = sizeof(alphanum) - 1;
char genRandom()
{
return alphanum[rand() % stringLength];
}
int main()
{
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
while(true)
{
for (int x = 0; x < sLength; x++)
{
cout << genRandom();
}
cout << endl;
}
}
我正在寻找一种方法来将第一个(用户定义的数量)字符存储到一个字符串中,我可以用它来与另一个字符串进行比较。任何帮助将不胜感激。
最佳答案
只需添加
string s(sLength, ' ');
之前while (true)
, 改变
cout << genRandom();
到
s[x] = genRandom();
在你的循环中,删除 cout << endl;
陈述。这将通过将字符放入 s
来替换所有打印.
关于c++ - 在 C++ 中将字符存储到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5054924/