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);
> }
>
> 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
Is myLoc[] an automatic variable inside of this function? In that
case, the problem is that you never initialized myLoc[], and it
doesn't contain '\0's as needed to terminate the string. You can
initialize it using memset(), or you can add the '\0' to the next
character with
myLoc[myLoop+1]='\0';
after the myChar[0] assignment.
On a side note, you can eliminate myRand and myChar[] entirely, and
simply use
myLoc[myLoop]=(char)( rand() % 25 + 'A' );
<mode pedant="on">
Your code assumes ASCII character encoding. Changing the "magic
number" 65 into 'A' helps make the code cleaner IMO, but it still
assumes the capital leters are contiguous.
</mode>
--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h> |
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:ThisIsASpamTrap@[EMAIL PROTECTED]
>
--
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.


|