I find myself often using variables that contain a very small range of numbers (typically from 1 to 10) and would like to minimize the amount of memory I use by using the char data type instead of int or even short. I would like to cin values to my char variables without having cin converting it to it's ASCII equivalent and without working with single quotes. Ie, the following:
cout<< "Pick from 1 to 10.";
char selection;
cin>> selection;
if (selection == 1) return 1;
etc...
Is there a common way of doing this? Again, I don't want to use single quotes.
Thanks
cin with Member Functions The cin object can also be used with other member functions such as getline() , read() , etc. Some of the commonly used member functions are: cin. get(char &ch): Reads an input character and stores it in ch .
A character can be a single letter, number, symbol, or whitespace. The char data type is an integral type, meaning the underlying value is stored as an integer.
C uses char type to store characters and letters. However, the char type is integer type because underneath C stores integer numbers instead of characters.In C, char values are stored in 1 byte in memory,and value range from -128 to 127 or 0 to 255.
Check if input is numeric: There is no way to check if input is numeric, without taking input into a char array, and calling the isdigit() function on each digit. The function isdigit() can be used to tell digits and alphabets apart.
You can create a little utility function:
struct CharReader {
char &c;
CharReader(char &c) : c(c) {}
};
CharReader asNumber(char &c) {
return CharReader(c);
}
template <typename T, typename Traits>
std::basic_istream<T, Traits>& operator>> (std::basic_istream<T, Traits> &str, const CharReader &c) {
short i;
str >> i;
c.c = static_cast<char>(i);
return str;
}
You can the use it like this:
char selection;
std::cin >> asNumber(selection);
There is no point in saving three bytes (or zero, because it's likely the compiler will align the stack anyway...) and complicating your code to read a number. Just do it normally and put your memory-saving efforts where it matters (if you don't know where it matters, it probably doesn't matter).
int selection;
if(!(cin >> selection) || selection < 0 || selection > 10) {
// hmmm do something about it; perhaps scold the user.
}
place_where_it_is_getting_stored = selection;
char selection;
cin >> selection;
selection -= '0';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With