Talk About Network

Google


Register and Login
Nick
Password
Register create new account Sign up is FREE and you can post replies, new topics, bookmark posts and more!
Recover lost password


Programming > C Moderated > Re: Sorry, newb...
Latest [ Topics | Posts ] Archive Post A New Topic Post a Reply
<< Topic < Post Post 2 of 12 Topic 1058 of 1126
Post > Topic >>

Re: Sorry, newbie question about generating a random string

by Keith Thompson <kst-u@[EMAIL PROTECTED] > Mar 17, 2008 at 03:19 PM

Scooter <slbentley@[EMAIL PROTECTED]
> writes:
> 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++) {
>         myRand =3D rand() % 25 + 65;
>         myChar[0] =3D (char)myRand;
> 	myLoc[myLoop] =3D  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=C2=A6=0EB
> VDYWQ=0EB
> VDYWQAB
> VDYWQAE
> VDYWQAEM=C3=BC=0EB
> VDYWQAEMQ=0EB
> VDYWQAEMQJB

In this newsgroup, comp.lang.c.moderated, each response has to wait
for the moderator to approve and post it.  That means any
back-and-forth discussion can take a very long time.  You might
consider posting to comp.lang.c instead; it's a lot noiser, but it's
quicker.  There are plenty of experts in both (mostly the same
people).

The output you showed us has one line for each iteration of your loop.
In other words, it indicates that you must have written a new-line
character each time.  The code you showed us doesn't do that.  I
conclude that you've shown us something other than your actual code.
Don't do that; we can't possibly guess which errors in your posted
code are actually relevant to your problem.  Post an *exact*
*complete* *compilable* program.  Copy-and-paste it; don't re-type it,
and don't paraphrase it.

(You did show us the output you expected and the ouput you actually
got; that's very good, and better than a lot of people do.)

Read <http://www.catb.org/~esr/faqs/smart-questions.html>
for lots of
similar good advice.

You declare myChar as a single-element array.  There's no reason for
it to be an array.  Declare it as an object of type char.  (You
actually don't need it at all; I'll get to that.)

In "srand((unsigned int)time(0))", the cast is unecessary.  In fact,
*most* casts are unnecessary.  Usually the language defines implicit
conversions that will do just the right thing; by using a cast, you're
often more likely to interfere with the compiler and introduce
possible bugs than to do anything useful.  In this case, the value
returned by the time function (of type time_t) will be implicitly
converted to type unsigned int (the type expected by the srand
function).  How does the compiler know to do this?  Because you showed
it the correct declarations of the time and srand functions by putting
this:
    #include <time.h>
    #include <stdlib.h>
at the top of your program.  If you *didn't* do this, you need to (the
compiler won't necessarily complain if you forget, so you'd better
remember).  You'll also need
    #include <stdio.h>
for the printf function.

Personally, I find "time(NULL)" clearer than "time(0)", but both are
valid.

rand() % 25 yields one of 25 values in the range 0 to 24.  If you're
trying to generate random English letters, you want rand() % 26,
unless you dislike the letter 'Z' for some reason.

The distribution of the random values may not be very good.  See
question 13.16 of the comp.lang.c FAQ, <http://www.c-faq.com/>,
for
more information.  In fact, see the entire FAQ.  It's an excellent
resource (though not a good way to learn C from scratch; for that I
recommend K&R2).

Where the heck does the value 65 come from?  Yes, I know, it's the
ASCII code for 'A'.  So write 'A' rather than 65; it makes your code
*much* easier to read.

(Note that the standard doesn't require the ASCII character set, and
in particular it doesn't require the letters to have consecutive
codes.  The EBCDIC character set, used on IBM mainframes, has gaps
between letters.  Your method for generating random letters will
probably work on any system you're likely to encounter, but it's not
****table.  There are other methods that don't depend on the letters
being contiguous.  I suggest you keep this in the back of your mind
and come back to it later after you've fixed the other problems.)

In "myChar[0] =3D (char)myRand;", again, the cast is unnecessary.
myChar[0] is of type char, so the value of myRand will be implicitly
converted to that type.  Assuming you've declared myChar as a char,
not as an array, this could be "myChar =3D myRand;".

You do in three lines what you could do more easily in one:

    myRand =3D rand() % 25 + 65;
    myChar[0] =3D (char)myRand;
    myLoc[myLoop] =3D  myChar[0] ;

You assign a value to myRand, then copy that value to myChar[0], then
copy that value to myLoc[myLoop].

Sometimes using a tem****ary variable to store the result of a
subexpression can make your code clearer; it breaks up the expression
into simpler chunks, and gives meaningful names to parts of it.  In
this case, though, it doesn't really help, especially after you
simplify the part of the expression by dropping the cast and not
making myChar an array.  With those simplifications, all three lines
can be collapsed to:

    myLoc[myLoop] =3D rand() % 25 + 65;

Note that here I've only simplified the expressions; I haven't
corrected some other errors.  I leave that to you.

And finally, we get to the problem that's actually causing the symptom
you're asking about.

    printf("%s", myLoc);

If you call printf() with a "%s" format, it expects a pointer to a
string as the next argument.  A string in C is *not* just an array of
characters; quoting the standard, it's "a contiguous sequence of
characters terminated by and including the first null character".
You've never stored a null character into your myLoc array, and
everything past the values you have stored will be garbage.  (Some
people use the phrase "random garbage", but it's arbitrary, not
random; assume it will be whatever is most inconvenient for you.
Murphy's Law applies.)  Some operations on strings (functions like
strcpy(), strcat(), and so forth) will guarantee that those strings
will always have a terminating null character ('\0'), but you're
assigning values to individual characters, so you don't get that
guarantee.  You'll need to store the '\0' explicitly, immediately
*after* the location where you just stored a random character.

You should use "%s\n" rather than "%s" if you want each string to
appear on a line by itself.  Or you can use puts() rather than
printf(), but for a novice it might be easier to use printf() for
everything.

Finally, since the "main" function is declared to return an int, it
should do so; 0 is a reasonable value to return.

--=20
Keith Thompson (The_Other_Keith) <kst-u@[EMAIL PROTECTED]
>
Nokia
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"
-- 
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.
 




 12 Posts in Topic:
Sorry, newbie question about generating a random string
Scooter <slbentley@[EM  2008-03-08 12:21:06 
Re: Sorry, newbie question about generating a random string
Keith Thompson <kst-u@  2008-03-17 15:19:13 
Re: Sorry, newbie question about generating a random string
=?utf-8?Q?Dag-Erling_Sm=C  2008-03-28 19:20:30 
Re: Sorry, newbie question about generating a random string
Keith Thompson <kst-u@  2008-03-30 14:58:21 
Re: Sorry, newbie question about generating a random string
Jack Klein <jackklein@  2008-03-17 15:19:52 
Re: Sorry, newbie question about generating a random string
Jonathan Leffler <jlef  2008-03-17 15:21:03 
Re: Sorry, newbie question about generating a random string
Barry Schwarz <schwarz  2008-03-17 15:21:22 
Re: Sorry, newbie question about generating a random string
Carl Barron <cbarron41  2008-03-17 15:21:31 
Re: Sorry, newbie question about generating a random string
Francis Glassborow <fr  2008-03-17 15:21:40 
Re: Sorry, newbie question about generating a random string
Kenneth Brody <kenbrod  2008-03-17 15:22:01 
Re: Sorry, newbie question about generating a random string
Vinicius Pinto <vinici  2008-03-17 15:22:07 
Re: Sorry, newbie question about generating a random string
David Thompson <dave.t  2008-03-28 19:20:14 

Post A Reply:
  Go here to Signup

AddThis Feed Button


About - Advertising - Contact - Frequently Asked Questions - Privacy Policy - Terms of Use - Signup

Contact
tan12V112 Wed Jul 9 0:33:48 CDT 2008.