C ++ How to cin a char as a number instead of a character

I often find myself using variables that contain a very small range of numbers (usually 1 to 10) and would like to minimize the amount of memory that I use by using the char data type instead of int or even short. I would like to assign values ​​to my char variables without converting cin to AECII equivalent and without working with single quotes. That is, the following:

cout<< "Pick from 1 to 10."; char selection; cin>> selection; if (selection == 1) return 1; 

etc...

Is there a general way to do this? Again, I don't want to use single quotes.

thanks

+4
source share
4 answers

It makes no sense to save three bytes (or zero, because most likely the compiler will align the stack anyway ...) and complicates your code reading the number. Just do it fine and make your efforts to save memory 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; 
+3
source

You can create a small useful 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; cc = static_cast<char>(i); return str; } 

You can use it like this:

 char selection; std::cin >> asNumber(selection); 
+3
source
 char selection; cin >> selection; selection -= '0'; 
+1
source

maybe you should try

 if (selection - '0' == 1) return 1; 

this is the easiest way in your environment

-1
source

All Articles