Can You Fix My Code Please Scope Issues

I'm trying to make a random string generator but i keep getting the error that a variable wasn't declared in the function i used it in even though my variable was declared in the heap. Thank You In Advance.




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
45
46
47
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cstdio>

static const char alphanum[3][26] = {
		{'0','1', '2','3','4','5','6','7','8','9'},
		{'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'},
		{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}
}; 

void alphaGen(){
	for(int i = 0; i < 31; i++){
		int num1 = (rand() % 3);
		int num2 = (rand() % 27) - 1;
		if(num1 < 0 || num1 > 27){
			if(num1 < 0){
				num1++;
			} else if(num1 > 27){
				num1--;
			}
		} if(num2 < 0 || num2 > 27){
			if( num2 < 0){
				num2++;
			} else if(num2 > 27){
				num2--;
			}
		}
		int *generatedRandomNum1 = new int;
		generatedRandomNum1 = &num1;
		int *generatedRandomNum2 = new int;
		generatedRandomNum2 = &num2;
	}
}

void keygen(int sum){
	alphaGen();
	char Key[sum];
	for(int c = 0; c < sum; c++){
		Key[c] = alphanum[generatedRandomNum1][generatedRandomNum2];
	} std::cout << Key[sum] << std::endl;
}

int main(int argc, const char *argv[]){
	keygen(10);
}
Last edited on
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
#include <iostream>
#include <string>
#include <random>
// #include <cstdlib>
// #include <ctime>

char random_char() {
    
    // https://cal-linux.com/tutorials/strings.html
    static const std::string alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" ;
    
    // http://en.cppreference.com/w/cpp/numeric/random
    static std::mt19937 rng( std::random_device{}() ) ;
    static std::uniform_int_distribution<std::size_t> distr( 0, alphabet.size()-1 ) ;

    return alphabet[ distr(rng) ] ;

    // or using the legacy rng:
    // return alphabet[ std::rand() % alphabet.size() ] ;
}

std::string random_string( std::size_t sz ) {

    std::string str ;
    while( str.size() < sz ) str += random_char() ;
    return str ;
}

int main() {
    
    // std::srand( std::time(nullptr) ) ; // if using the legacy rng:
    for( int i =0 ; i < 10 ; ++i ) std::cout << random_string(20) << '\n' ;
}

http://coliru.stacked-crooked.com/a/53f4dc19edeecc0f
Topic archived. No new replies allowed.