Viktor Viktor - 1 year ago 74
C++ Question

How can i generate random char from variable

I have two char string and they have '-' and '+' sign.

I want to pick a random sign from a variable. So far i tried like this, but it outputs only '+' - sign, how can i make it correct?

char rand_symb;
char plus = '+';
char minus = '-';
rand_symb = rand() % (plus - minus + 1) + minus;

Answer Source

You're choosing between two values, so you need to generate two random values. It's simplest to just generate 0 and 1:

int value = rand() % 2;

(Yes, rabid purists will tell you that this is doomed, because rand() sucks, but it's good enough for what you're currently doing).

Based on that value, pick one of the two characters:

char ch = value ? '+' : '-';

or, to make the whole thing more compact:

char ch = rand() % 2 ? '+' : '-'.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download