You need to terminate the string with '\0', after adding the
character. Also, you don't need the '[1]' when declaring a char and
you can make your program more clear getting rid of myChar and myRand,
like this:
myLoc[myLoop] =3D rand() % 25 + 65;
myLoc[myLoop+1] =3D '\0';
printf("%s\n", myLoc);
On Mar 8, 3:21=A0pm, Scooter <slbent...@[EMAIL PROTECTED]
> 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 =3D 0; myLoop < 10; myLoop++) {
> =A0 =A0 =A0 =A0 myRand =3D rand() % 25 + 65;
> =A0 =A0 =A0 =A0 myChar[0] =3D (char)myRand;
> =A0 =A0 =A0 =A0 myLoc[myLoop] =3D =A0myChar[0] ;
> =A0 =A0 =A0 =A0 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=A6 B
> VDYWQ B
> VDYWQAB
> VDYWQAE
> VDYWQAEM=FC B
> VDYWQAEMQ B
> VDYWQAEMQJB
> --
> comp.lang.c.moderated - moderation address: c...@[EMAIL PROTECTED]
-- you
must
> have an appropriate newsgroups line in your header for your mail to be
see=
n,
> or the newsgroup name in square brackets in the subject line. =A0Sorry.
--
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.


|