Reputation: 1597
So right now I have this code that generates random letters in set increments determined by user input.
#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;
}
}
I'm looking for a way to store the first (user defined amount) of chars into a string that I can use to compare against another string. Any help would be much appreciated.
Upvotes: 0
Views: 180
Reputation: 58677
#include<algorithm>
#include<string>
// ...
int main()
{
srand(time(0)); // forget me not
while(true) {
cout << "What is the length of the string you wish to match?" << endl;
cin >> sLength;
string r(sLength, ' ');
generate(r.begin(), r.end(), genRandom);
cout << r << endl;
}
}
Upvotes: 0
Reputation: 30969
Just add
string s(sLength, ' ');
before while (true)
, change
cout << genRandom();
to
s[x] = genRandom();
in your loop, and remove the cout << endl;
statement. That will replace all of the printing by putting the characters into s
.
Upvotes: 2
Reputation: 25739
Well, how about this?
std::string s;
for (int x = 0; x < sLength; x++)
{
s.push_back(genRandom());
}
Upvotes: 1