Random String Generator in C++

Hi there,

I need some help with my code.
It is a random string generator which works perfect.
However there is one problem.
I want to get the string in my memory using
cin, getline, scanf, or whatever, but that
doesn't work. Can someone tell me how to get
the string I generated and how to store it in a variable?

CODE:"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#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()  // Random string generator function.
{

    return alphanum[rand() % stringLength];
}

int main()
{
    srand(time(0));
    for(int z=0; z < 21; z++)
    {
        cout << genRandom();

    }
    return 0;

}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
// If you use C's char arrays:
char String[128] = {0};
for(unsigned int i = 0; i < 21; ++i)
{
    String[i] = genRandom();
}
// If you use C++'s std::string:
std::string Str;
for(unsigned int i = 0; i < 21; ++i)
{
    Str += genRandom();
}


Also pointing out:

1
2
3
4
return alphanum[1+(rand()%sizeof(alphanum)) % stringLength];
// Because of this, the very first character will never be taken/used/printed
// Use this instead, which is also faster:
return alphanum[rand() % stringLength]
Last edited on
Thanks for your reply (:

code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#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()
{
    srand(time(0));
    std::string Str;
    for(unsigned int i = 0; i < 20; ++i)
    {
    Str += genRandom();

    }
    cout << Str << endl;
    


}


    
    // THANKS FOR THE HELP EssGeEich!

    return 0;

}

Last edited on
mausy131 wrote:
// THANKS FOR THE HELP EssGeEich!

Lol, no need at all.
Topic archived. No new replies allowed.