954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How i can to generate characters of 'n' lenght using letters and numbers by rand()

I have that funtion for generate sequence to the style 'hqhzaw', 'ebcpm', 'qtch', etc. (only letters) and according to 'lenght'

string random_letter(int length) {
	string s;

	for (int i = 0; i < length; i++) {
       		s += char(rand() % 26 + 97);
	}

	return s;
}

I want to generate, using this funtion or some other, array of letters and numbers to the style 'tn4v9k2e0', '8ezt0p3', 5cye7' according to 'lenght'.

Thanks.

rafaelbrizu
Newbie Poster
2 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

instead of using the ascii codes which would get a bit more complicated when you add numbers because of the disconnect between the codes (since numbers are 48-57 and letters 97-122), why don't you try something like the following as a starting point:

string random_letter(int length) 
{
     const string values = "abcdefghijklmnopqrstuvwxyz";
     const int valuesSize = 26;
     string s;

     for (int i = 0; i < length; i++) 
     {
          s += values[rand() % valuesSize];
     }

     return s;
}


then you can add whatever characters you want (numbers), just a suggestion.

~J

jesseb07
Junior Poster
111 posts since Dec 2006
Reputation Points: 76
Solved Threads: 15
 

Thank you. Works very well for me.

rafaelbrizu
Newbie Poster
2 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You