I found this code in a different topic and i was a little confused on how it works. How does it create random letters when the only letter involved is 'a'. I thought you would need to have the whole alphabet in a string or something.
1 2 3 4 5 6 7 8 9
char c;
int r;
srand (time(NULL)); // initialize the random number generator
for (i=0; i<num; i++)
{ r = rand() % 26; // generate a random number
c = 'a' + r; // Convert to a character from a-z
cout << c;
}
the thing about coding is that you have to be as lazy as possible
r = rand() % 26;
this will set the r value assigned randomly from 0-25
c = 'a' + r;
This will set the value of char c from a + (0 to 25)... the integer value of a is 97 (it actually doesn't matter here)... the add 25 (upper limit) to it you'll get z (ascii value 122).... in between you'll get the other characters randomly.....
#include <iostream>
#include <string>
#include <cctype>
#include <ctime>
usingnamespace std;
void x(char s, int n, int e);
int main() {
char c='\n';
int num=7;
int r=0;
x(c, num, r);
system("pause");
return 0;
}
void x(char s, int n, int e) {
srand((unsignedint)time(0)); // initialize the random number generator
for (int i = 0; i < n; i++)
{
e = rand() % 26; // generate a random number
s = 'a' + n; // Convert to a character from a-z
cout << (s);
}
}
That is called type-cast. It casts a value from an (int) to a (char).
http://www.cprogramming.com/tutorial/lesson11.html
You can also try removing the (char) type cast all you want. If the output is the same, then good for you. But if the output is a set of only digits, you should keep the (char) part.