Reputation: 79
I'm trying to store a number as a character in a char vector named code
code->at(i) = static_cast<char>(distribution(generator));
However it is not storing the way I think it should
for some shouldn't '\x4' be the ascii value for 4? if not how do I achieve that result?
Here's another vector who's values were entered correctly.
Upvotes: 0
Views: 199
Reputation: 385088
No. \xN
does not give you the ASCII code for the character N
.
\xN
is the ASCII character† whose code is N
(in hexadecimal form).
So, when you write '\x4'
, you get the [unprintable] character with the ASCII code 4. Upon conversion to an integer, this value is still 4.
If you wanted the ASCII character that looks like 4
, you'd write '\x34'
because 34 is 4
's ASCII code. You could also get there using some magic, based on numbers in ASCII being contiguous and starting from '0'
:
code->at(i) = '0' + distribution(generator);
† Ish.
Upvotes: 3
Reputation: 212929
You are casting without actually converting the int to a char. You need:
code->at(i) = distribution(generator) + '0';
Upvotes: 3