how do i randomly generate 2 chars?

I want to generate 2 chars
F or Q

How do I do this?
I don't want to print the whole alphabet.

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
   srand( time(0) );
   if ( rand() % 2 )   cout << "F";
   else                cout << "Q";
}
I want to store that result into my one variable.

Should I make a Value returning function, whatever I get from the If statement is returned then use my variable to catch it?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

char randChar()
{
   if ( rand() % 2 )   return 'F';
   else                return 'Q';
}

int main()
{
   srand( time(0) );
   
   char c = randChar();
   cout << "Character is " << c;
}
 
    char letter = (rand() % 2) ? 'F' : 'Q';
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
   char opt[] = {'F','Q'};
   srand( time(0) );
   cout << "Character is " << opt[ rand() % 2 ];
}
The rand() has deprecated status in C++ standard. The replacement is a bit more verbose:

http://www.cplusplus.com/reference/random/bernoulli_distribution/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>
#include <chrono>
#include <random>

int main()
{
  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
  std::default_random_engine generator( seed );
  std::bernoulli_distribution distribution( 0.5 );

  if ( distribution(generator) ) std::cout << 'F';
  else std::cout << 'Q';

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