Generate random chars and integers in C++
How do I generate random chars and integers within a method so that the method can be called in main() and so that the method generat开发者_StackOverflow中文版es random chars and integers together. I do not want a method that genrates chars and another methods that generates integers.
You can write a method like (assuming you want only lower case English characters, you can extend it):
void generate(char& ranChar, int& ranNmber)
{
//Generate a random number in the range 0-25 and add the ascii value 'a'
ranChar = rand() % 26 + 'a';
ranNumber = rand();
}
int main()
{
//Seed the random number generator with the current time
srand(time(NULL));
char ch;
int n= 0;
generate(ch,n);
return 0;
}
You could use boost::tuple, like this:
boost::tuple<int, char> gen () {
// srand() etc
return make_tuple(rand(), (rand() % ('z' - 'a' + 1)) + 'a');
}
精彩评论