how can i convert the 2 and 3 to an int of value 23?
A simplistic way of doing it is shown below (untested). The idea is that you initialize an accumulator to zero and then when a digit key is received you multiply the accumulator by 10 and add in the value of the just-received key.
I call this simplistic because it has several shortcomings:
- It doesn't allow "editing" the value, i.e. it doesn't support backspacing to correct an entered value but you could add that.
- It ignores unsupported keys. You may want to add some user feedback indicating that an invalid key was pressed.
- It returns zero if the Enter key is pressed with no preceding digit keys. You may want to ignore the enter key in that case. The variable 'valKeys' indicates the number of valid digit keys that have been seen.
- It doesn't handle overflow. If you press the 9 key 99 times and then Enter, the value returned will not be correct. You could add user feedback indicating an error after a certain number of digits have been received. The unsigned long accumulator can handle up to 9 arbitrary digits, representing values up to 999,999,999.
The ideas in this code can be used to implement a similar function to support floating point value entry using, for example, the asterisk to represent the decimal point.
// Get an unsigned integer value from the keyboard terminated by an Enter key.
// All non-numeric keys (other than Enter) are ignored.
#define ENTER_KEY '#'
unsigned long val = 0;
unsigned valKeys = 0;
key = kpd.get_key();
if ((key >= '0') && (key <= '9'))
// add the key's value to the accumulator
val = (val * 10) + (key - '0');
else if (key == ENTER_KEY)