There is a function for this in the C standard library (there may be a C++ version too, you'd have to look).
#include <stdlib.h>
void srand(unsigned int seed); // seeds the random number generator
int rand (void); // returns a random number in the range 0 to RAND_MAX.
If you want a random number that falls within a certain range (e.g. character codes), be inventive! The following would place a random (lowercase) letter into char c (I initialize the random number generator with the current clock time, which is a good pseudo-random initialization vector):
#include <stdlib.h>
#include <time.h>
char c;
srand( (unsigned int) time(NULL));
c = (rand() % 26) + 'a';
See how this works? It generates a random integer, takes its modulo 25 (so that it becomes an integer from 0 to 25), and then adds that value to the ASCII representation of the letter 'a'. That way you will always be guaranteed to get a value between 'a' and 'z'.
See the GNU C documentation:
http://www.gnu.org/s...html#ISO-Random
http://www.delorie.c...c/libc_682.html
This is a good idea but you forgot one thing.
(rand() % 26) + 'a' will give you an integer value. You would want to cast it to a char:
c = (char) (rand() % 26 + 'a');
If you want to include numbers and capital letters too, you could do something similar to this:
#include <iostream>
#include <ctime>
using namespace std;
int main() {
srand((unsigned) time(NULL));
const int passLen = 10;
for (int i = 0; i < passLen; i++) {
cout << (char) (rand() % ('z' - '0' + 1) + '0');
}
}
On the ASCII table, out of numbers, lower case letters and uppercase letters, numbers have the lowest ASCII value, then capital letters, then lowercase letters. So the lowest we would want is
'0', and the highest we would want is
'z'.
Hope this helps!