开发者

Generate random chars and integers in C++

开发者 https://www.devze.com 2022-12-12 14:41 出处:网络
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

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');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消