Generate fixed-length string containing random digit.

G

Guest

Hi,
I am new to C. How to generate an fixed-length string containing an random
digits? for example string of 5 characters, the value can be 03234 or 23423
or 02343

Thanks
Tran Hong Quang
 
B

Bruno van Dooren

Hi,
I am new to C. How to generate an fixed-length string containing an random
digits? for example string of 5 characters, the value can be 03234 or
23423
or 02343


Hi,

something like this should do the trick

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main( void )
{
int i;
char randString[6] = "";

srand( (unsigned)time( NULL ) );
i= rand() ;
sprintf(randString, "%5d", i);
}

this example gets a random number (an integer) and prints the first 5
characters in your fixed size string.
temember that you need an extra character to allow for null
termination.hence randString[6] instead of randString[5].

--

Kind regards,
Bruno.
(e-mail address removed)
Remove only "_nos_pam"
 
D

David Wilkinson

Bruno said:
Hi,
I am new to C. How to generate an fixed-length string containing an random
digits? for example string of 5 characters, the value can be 03234 or
23423
or 02343



Hi,

something like this should do the trick

#include <stdlib.h>
#include <stdio.h>
#include <time.h>

int main( void )
{
int i;
char randString[6] = "";

srand( (unsigned)time( NULL ) );
i= rand() ;
sprintf(randString, "%5d", i);
}

this example gets a random number (an integer) and prints the first 5
characters in your fixed size string.
temember that you need an extra character to allow for null
termination.hence randString[6] instead of randString[5].

Bruno:

Shouldn't that be

sprintf(randString, "%05d", i);

David Wilkinson
 
B

Bruno van Dooren

this example gets a random number (an integer) and prints the first 5
characters in your fixed size string.
temember that you need an extra character to allow for null
termination.hence randString[6] instead of randString[5].

Bruno:

Shouldn't that be

sprintf(randString, "%05d", i);

David Wilkinson

you are partially right. there is still a second problem with my example :)
doing it like this assures only that there are minimum 5 characters, all of
which will have
a numerical value between 0 and 9.

if i has more than 5 decimal digits it would try to print out all characters
with a buffer overflow as the result.

to do it correct you have to make sure that i is never more than 5 digits.
the correct solution in that case is this:
sprintf(randString, "%05d", i%100000);

That'll teach me to post an example without testing it first ... :)

--

Kind regards,
Bruno.
(e-mail address removed)
Remove only "_nos_pam"
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top