Scooter wrote:
> I'm trying to write a simple program to generate a random string. I
> have what seems to work, although I'm guessing there are better ways
> to do it. But my overall goal is to generate a random character, then
> add a second random character to it, then another, etc. until the
> string grows to a max of 10 characters. I'm testing a word wheel on a
> website but have to use 'C' and it is not my forte'. Anyway, here's
> what I have:
>
> int myRand,myLoop;
> char myChar[1];
> char myLoc[11];
>
> srand((unsigned int)time(0)); //Seed number for rand()
>
> for (myLoop = 0; myLoop < 10; myLoop++) {
> myRand = rand() % 25 + 65;
> myChar[0] = (char)myRand;
> myLoc[myLoop] = myChar[0] ;
> printf("%s", myLoc);
> }
>
Since myLoc is not initialized, you get garbage in it.
It so happens that the garbage is zero at first, but then it isn't.
Use: printf("%.*s\n", myLoop + 1, myLoop);
That says print just the first N+1 characters on the Nth iteration of
the loop - plus add a newline which you seem to be missing.
You really don't need myChar or myRand at all; you can simply assign the
computed value to myLoc[myLoop].
And, personally, I find 'my' as a prefix for variables extremely ...
well, maybe unusual is the best word. I'd hate to look at large
quantities of code written using that as a naming convention.
> I would expect the output to look something like:
> V
> VD
> VDY
> VDYW
> VDYWQ
> VDYWQA
> VDYWQAE
> VDYWQAEM
> VDYWQAEMQ
> VDYWQAEMQJ
>
> But instead it looks more like:
> V
> VD
> VDY
> VDYW¦B
> VDYWQB
> VDYWQAB
> VDYWQAE
> VDYWQAEMüB
> VDYWQAEMQB
> VDYWQAEMQJB
--
Jonathan Leffler #include <disclaimer.h>
Email: jleffler@[EMAIL PROTECTED]
jleffler@[EMAIL PROTECTED]
of DBD::Informix v2008.0229 -- http://dbi.perl.org/
publictimestamp.org/ptb/PTB-2708 tiger 2008-03-09 00:00:07
7C445449CF49510AF9B5D5662A79CACBD2723E8EF5C7EDB9
--
comp.lang.c.moderated - moderation address: clcm@[EMAIL PROTECTED]
-- you must
have an appropriate newsgroups line in your header for your mail to be
seen,
or the newsgroup name in square brackets in the subject line. Sorry.


|