468,496 Members | 1,798 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,496 developers. It's quick & easy.

How would you create a random string of data

I have a program that takes data entered from a keyboard and uses it as a random seed value, is there anyway to generate a string of up to 80 characters that could be used in place of data entered from a keyboard?
Jul 26 '06 #1
3 6193
Banfa
9,055 Expert Mod 8TB
Here you go

"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw xyz0123456789AEIOUaeiou7654321"
Jul 26 '06 #2
axas
32
That is a string generator only for characters...

char s[80];
int i, val;
int ch1, ch2, num;

printf("Value: ");
scanf("%d", &val);

srand(val);

for (i = 0; i < strlen(s); i++) {
s[i] = rand() % 'z' + 'A';
if (s[i] > 'Z')
s[i] = 'A';
if (s[i] < 'A')
s[i] = 'Z';
}

s[i] = '\0';
Jul 27 '06 #3
Banfa
9,055 Expert Mod 8TB
That is a string generator only for characters...
Nice try but you have some errors

Expand|Select|Wrap|Line Numbers
  1. char s[80];
  2. /* We want a string of 80 characters.  Since it's a string 
  3.    there will need to be a NULL terminator (which you add).  
  4.    However that makes 80 characters + 1 NULL terminator = 81 
  5.    char required, your array is 1 char too small. */
  6. int i, val;
  7. int ch1, ch2, num;
  8.  
  9. printf("Value: ");
  10. scanf("%d", &val);
  11.  
  12. srand(val);
  13.  
  14. for (i = 0; i < strlen(s); i++) {
  15. /* Unfortunately s has not been initialised at this point 
  16.    so strlen(s) could return anything between 0 and the 
  17.    maximum value that size_t can hold (a very large number).  
  18.    I suggest sizeof s would be better here */
  19.     s[i] = rand() % 'z' + 'A';
  20. /* The low bits of the return value of rand() can be not 
  21.    very random so rand() % anything small is not very random.  
  22.    Also this expression results in a value between 
  23.    'A' and 'z' + 'A'  - 1 but imediately below any 
  24.    value > 'Z' is set to 'A'.  This will result in a more than 
  25.    50% chance that any character is 'A', not very random. */
  26.     if (s[i] > 'Z') 
  27.         s[i] = 'A';
  28.     if (s[i] < 'A') 
  29.         s[i] = 'Z';
  30. }
  31.  
  32. s[i] = '\0';
  33. /* Assuming you meant sizeof at this point i would be 
  34.    81 and you would be writing outside the array bounds 
  35.    and invoking undefined behaviour. */
  36.  
Jul 27 '06 #4

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by Roomates Computer | last post: by
2 posts views Thread by Shapper | last post: by
5 posts views Thread by Michael Sperlle | last post: by
7 posts views Thread by tamsun | last post: by
reply views Thread by Kim | last post: by
reply views Thread by NPC403 | last post: by
3 posts views Thread by gieforce | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.