How do you generate a random string?

I've got a bit of code here:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
using namespace std;
char rand_char()
{
srand(time(0));
int random = rand() % 52;
char random2=(char)(random+65);
return random2;
}
int main(int argc, char **argv)
{
int len;
cout<<"Please enter the lenth of the string: ";
cin>>len;
cout<<endl;
char password[len];
for(int i=0;i<len;i++)
{
random[i]=rand_char();
random[0]=toupper(password[0]);
cout<<password[i];
}
return 0;
}

The problem is that all the characters in the randomly generated string are the same(except the first one, I want it to be in upper case).
Can someone help me?
I would try only calling srand() once, at the beginning of your program.
srand only once. else you'll reseed the RNG everytime you call the function, on a fast pc that will cause the created numbers all be the same.
I would call srand exactly like this:

srand (time (NULL));
some random dude, srand() is called already, but it's being called again and again, that's why they told cppbeginner to take it out of the loop.. basically, it should probably be the first thing called in main outside of any loops, not because it should be first, but to make sure that they aren't calling it over and over again...
oh, note to self: read all the posts

=P
Here. Use code brackets. Look at the changes.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// CODE REPAIRED
// NO NEED FOR CSTDIO WITH IOSTREAM
#include <ctime>
#include <cstdlib>
#include <iostream>

using namespace std;

char rand_char()
{
  // REMOVED srand from this location
  // SIMPLIFIED FUNCTION
  return (char)( (rand() % 52) + 65);
}

int main(int argc, char **argv)
{
  // CALL srand ONCE at beginning of main!
  srand(time(0));

  // ------ This didn't change -- //
  int len;
  cout << "Please enter the length of the string: ";
  cin >> len;
  cout << endl;

  // -- Changes -- //

  //char password[len]; // ILLEGAL C++! Use std::string
  string password; // Better!

  for(int i = 0; i < len; i++)
  {
    // random? Where was this declared? Changed to password.
    /** random[i] = rand_char(); */// XXXX BAD XXXX

    // ADD RANDOM CHAR TO STRING VIA +=
    password += rand_char();
    if (i == 0) // case: So its not run for every character.
      password[i] = toupper(password[i]); // Upercase's the first char
  }

  // With string print all characters at once, easily.
  cout << password << endl;

  return 0;
}
Topic archived. No new replies allowed.