Saturday, May 22, 2010

Random String/Word Generator in C++?

I'm trying to figure out how to generate random words. They don't need to make sense. For instance: it can generate "dfgag" "sge" sdvbsvdv". It would be perferable to make it generate less than 7 chars.





I've tried looking online but I can't find anyone who has done this.





Does anyone have a function, a place online, or even pseudo code that can point me in the right direction?

Random String/Word Generator in C++?
#include %26lt;stdlib.h%26gt;


#include %26lt;time.h%26gt;





void rword (char *word)


{


int len = rand () % 6 + 1;


word [len] = 0;


while (len) word [--len] = 'a' + rand () % 26;


}





int main ()


{


char word[7];


srand(time(0));


while (1) {rword(word); printf ("%s\n", word);}


}
Reply:I would strongly encourage you to take a good C++ course or follow some tutorials.





#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;time.h%26gt;








static short getRandomNbr(short low, short high)


{


return(low + (short) ((double)(1 + high - low) * ((double)rand() / 100.0) / ((double)RAND_MAX / 100.0)));


} /* getRandomNbr() */








main()


{


register short i;


unsigned char answer[8];


unsigned int luck; // :)





memset(answer, 0, 8);





srand((unsigned int)(time((time_t *) 0)));





usleep((luck = 1000 + 80 * getRandomNbr(1, 10000)));





srand((unsigned int)(time((time_t *) 0)) + luck);





for (i = 0; i %26lt; getRandomNbr(1, 7); i ++)


{


answer[i] = (unsigned char) getRandomNbr((short)'a', (short)'z');


} // for





printf("%s\n", answer);





} // main()

garland flower

No comments:

Post a Comment