Is there any char data type alternative ( 1-byte value ) to represent numeric values?

Viewed 135

I've this issue:

#include <iostream>
int main() {
    unsigned char little_number_from_0_to_255 = 0;
    std::cout << "How old are you (for example)? _";
    std::cin >> little_number_from_0_to_255;
    std::cout << "You are " << little_number_from_0_to_255 << " year/s old.";
}

In brief, even if in this case what follows would'nt care much, i'd like to avoid the waste of 1 byte (if compared to a short int type) for each variable i need to store when its value is so tiny, but in all my attempts the un/signed char type variable is always interpreted as the ASCII representation of the first digit of the number I input the un/signed into.

Is there in C++ any good way to have a 1 byte data type, the value of could be only numeric (with all the arithmetic etc., like un/signed char) but without having to deal with the automatic ASCII representation (unlike un/signed char)?

If not, how could i "circumvent" the problem?

Is there a way to avoid that, even if I say that I'm 61, in the variable there will be 54 (decimal) and i will realize that i'm a liar 'cause in reality i'm only 6?

A way to say the computer that it has to grab the whole number and that it hasn't to look only at the first character input?

--I've already read of '+' just before the char variable, but this works only for output, and isn't my case.

1 Answers

Is there in C++ any good way to have a 1 byte data type, the value of could be only numeric (with all the arithmetic etc., like un/signed char) but without having to deal with the automatic ASCII representation (unlike un/signed char)?

You could define a wrapper class that stores a single byte integer type such as std::int8_t as a member, and implicitly converts to a non-character integer type such as int. Whether this is "good" is subjective and depends on use case.

If not, how could i "circumvent" the problem?

You can use an intermediate variable of non-character integer type when dealing with character streams:

std::uint8_t little_number_from_0_to_255 = 0;

// input
unsigned input;
std::cout << "How old are you (for example)? _";
std::cin >> input;
little_number_from_0_to_255 = input;

// output
unsigned output = little_number_from_0_to_255
std::cout << "You are " << output << " year/s old.";
Related