LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (https://www.linuxquestions.org/questions/linux-software-2/)
-   -   Produce random character with c program (https://www.linuxquestions.org/questions/linux-software-2/produce-random-character-with-c-program-184562/)

liguorir 05-22-2004 02:12 PM

Produce random character with c program
 
I need some advice on random characters.

Toshi3 05-22-2004 03:19 PM

Hi,

When you initiate the rand function with randomize (in stdlib) it uses the current time / date to make the number random. If you use srand to initiate the number, you would need to write something like srand((NULL)time())...
To produce the random char I would do something like this:

char c[] = {"abcde.....ABCDE.....?.,:$!"0123456789"} // all valid chars
int n = strlen(c); // #chars in c[]
int i = rand(); // a random number from 0 to 32767
i = i % n; // i will now be in the interval from 0 to n-1
c[i]; // will be a random char

However, it is possible to improve the quality of the random number by replacing
i = rand();
with
do { i = rand(); } while (i >= n * (int)(32768 / n)) ;

Hope this helps.

drigz 05-22-2004 03:26 PM

if you want a random ASCII char, i believe
char chr = (char) i
will work, where i is from 0 to 255

also, shouldn't this be in the programming forum?

8route 05-23-2004 08:57 AM

Here are some source codes
 
Here are some source codes

http://www.agner.org/random/

liguorir 05-23-2004 06:30 PM

Thanks for the advise


All times are GMT -5. The time now is 09:32 PM.