When var_name
is of type unsigned char
, then the line
std::cin >> var_name;
is similar to
std::scanf("%c", &var_name);
i.e. C++ will assume that you want to read a single character and write the character code into var_name
.
If you instead want to read a number and write that number into var_name
, then you cannot use the data type char
or unsigned char
when using operator >>
, even if the data type is technically able to represent the desired range of values. Instead, you will first have to use a variable with a larger data type, such as unsigned short
, for reading the number. Afterwards, you can assign it to another variable of type unsigned char
:
unsigned char var_name;
unsigned short temp;
std::cin >> temp;
if ( std::cin )
{
var_name = static_cast<unsigned char>( temp );
std::cout << var_name << '\n';
}
else
{
//TODO: handle error
}
The static_cast
is not necessary, but some compilers may emit a warning due to the truncation, which will probably be suppressed by the cast. Also, using the cast makes the code more readable, because it becomes obvious that the value is being truncated.
However, I generally do not recommend that you use operator >>
for user input, because it will do strange things, such as
- not always read one line of input at a time, and
- accept garbage such as
"6sdfj23jlj"
as valid input for the number 6
, although the input should probably be rejected in this case.
If you want to read a number from the user with proper input validation, I recommend that you take a look at my function get_int_from_user
in this answer of mine to another question.