I've previously asked a question related to generating a random unsigned char and pretty good suggestions came along the way however due to simplicity I've applied ;
srand((unsigned)time(NULL));
rand()%256;
I call the srand one time at the beginning of the program, however I keep getting '?' for a random char. Not all the time but most of the time and that causes me to lose my focus.
Most probably you keep getting random chars that your terminal does not need how to print and outputs ?
. Try converting them to int
before printing:
std::cout << (int)my_random_char;
int
comes into play. If what you want are real characters, then consider using only the printable subset - David Rodríguez - dribeas 2012-04-04 17:25
You're not getting '?' as a character, it is being printed that way because the character selected isn't printable. Print it as an integer and you will see that the value is random as you would expect.
Depending on your platform the values [128 255] may not be valid characters on their own. If you want a random, printable ascii character then you need to generate chars in the range [32 127).
Here's code modified from my answer to your other question, to select only printable ascii characters.
int main() {
std::random_device r;
std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
auto rand = std::bind(std::uniform_int_distribution<char>(' ','~'),
std::mt19937(seed));
std::generate_n(std::ostream_iterator<char>(std::cout," "), 25, rand);
}
A few things to consider:
srand()
before each invocation of rand()
. Call it once when your program starts (if you really want to).Unsigned chars are not characters; they're bytes. You're getting random bytes between 0 and 255 (inclusive), and some of these (or most, depending on encoding) are not valid characters.
If you want a random character between a and z, for example, use something like
unsigned char c = 'a' + rand() % 26;
(rand() % 26
is not the recommended way of doing this, but it's good enough for most applications. See the manpage.)
?
(ASCII value 63)? Or are you just printing the character? If so, then it's possible that any non-ASCII values (such as the range 128-255) are printed as?
. Try converting toint
before printing it - Mike Seymour 2012-04-04 17:09