generating random characters not numbers with rand()
can anyone tell me how can i generate random character with the rand() function.
I know how to generate random number but not characters.
Thanks for your help
If you just want random characters between 'a' and 'z', do:
or better yet ... between a range of characters:
char rnd_char(){ return (char)( ( rand() % 26 ) + 'a' );}
or better yet ... between a range of characters:
char rnd_char( char low, char high ){ return (char)( ( low <= high ) ? rand() % ( high - low + 1 ) + low : rand() % ( low - high + 1 ) + high );}
Something like this c++ code should help you
hope this is what you're after :)
edit: damn too slow :)
#include <stdlib.h>#include <stdio.h>int main( int argc, char *argv[] ){ static const char cList[] = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; // Generate strings of 10 chars char cBuf[11]; for (int i = 0; i < 10; i++) cBuf = cList[rand() % (sizeof(cList)-1)]; // insert term char cBuf = '\0';}
hope this is what you're after :)
edit: damn too slow :)
Simply create a random number in the range [0,255] and store it in a char.
If you only want a subset of the characters [say, letters and numbers but not punctuation], use a smaller range [in this case 62, ten for numbers and twenty-six each for upper and lower case letters] and write a simple mapping.
*edit: Actually, I like technomancer's solution better. Its more general, and easier to add in individual characters. That's going in my bag of tricks :)
CM
If you only want a subset of the characters [say, letters and numbers but not punctuation], use a smaller range [in this case 62, ten for numbers and twenty-six each for upper and lower case letters] and write a simple mapping.
int number = rand() % 62; //Not the best way to limit the range, I knowchar character;if(number < 10) { //this corresponds to digits character = (char)number + '0';} else if(number < 36) { //capital letters character = (char)number + 'A';} else { //lower case letters character = (char)number + 'a';}
*edit: Actually, I like technomancer's solution better. Its more general, and easier to add in individual characters. That's going in my bag of tricks :)
CM
Quote:Original post by technomancer
Something like this c++ code should help you
*** Source Snippet Removed ***
hope this is what you're after :)
edit: damn too slow :)
STL'd!!!11
#include <string>using std::string;string randString(int length) { static const string cList = "0123456789" "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; string result(length, '\0'); for (int i = 0; i < 10; i++) { result = cList[rand() % cList.length()]; } return result;}
[grin]
[grin]
From,
Nice coder
char random[255]for (int x = 0;x < 254;x++) random[x] = rand() % 255;random[255] = '\0';
[grin]
From,
Nice coder
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement