Store output of a function into a string

Hi I found a function online that generates a random string of characters and outputs them. How can I store them in a string rather than outputting them. Sorry I'm new to C++ and I haven't done it in about a year.

Here is the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
static const char alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"!£$%^&*()_+=-{}[]@:;#~?/>.<,\|`¬";

int stringLength = sizeof(alphanum) - 1;

char genRandom()  // Random string generator function.
{

    return alphanum[rand() % stringLength];
}


If anyone can help me then I would really appreciate it :)
std::string mystring = yourFunction();
Cheers but I had already tried that and it didn't work. It said 'invalid conversion from 'char' to 'const char'
Could post the function definition? That's really the only important part.

EDIT:
Oh wait, this is weird. alphanum and stringLength are globals. I see what's going on now.

std::string mystring = genRandom(); should work...

std::string::operator= takes a char, genRandom() is returning a char. Can you post the code you did that failed?

Also,

Should alphanum be defined as:

1
2
3
4
5
6
static const char* alphanum[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"!£$%^&*()_+=-{}[]@:;#~?/>.<,\|`¬";
Last edited on
Why the C-string? Why not a std::string?
1
2
3
4
5
6
static const std::string alphanum =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"!£$%^&*()_+=-{}[]@:;#~?/>.<,\\|`¬"; // Don't forget to escape the escape character. 


Then there would be no need for the stringLength variable since a std::string knows it's own size.

Should alphanum be defined as:

No, this is a single C-string, not an array of C-strings.
Last edited on
Basically I just want to store the random characters from this program that I found into a string. http://www.cplusplus.com/forum/windows/88843/
What have you tried?
I've just tried
 
string x = getRandom();
That will assign a character to the string, wiping out whatever was in the string.

Did you go back and check the original post you copied the code from?
http://www.cplusplus.com/forum/windows/88843/#msg477438

At line 27 in that post:
 
   Str += genRandom();

Note that the above code APPENDS a character to the string rather than assigning a character to the string.


Topic archived. No new replies allowed.