Your variable
item_type
is an integer. So when the user types in a value for it the compiler converts whatever the user types directly into a binary number. Doing it that way means that you loose the original characters that the user typed in.
If you make
item_type
a char, then you retain the character that is typed in but you have limited your numerical range to between 0 and 9.
So my option is to read in a
std::string
, which captures what the user inputs without modifying it so that we can test what the user entered before deciding how to convert it to our integer
item_type
.
With a
std::string
like
item_type_str
you can find out how many letters it contains with the
size()
function:
if(item_type_str.size() == 1) // test if only a single character was entered.
You can access each individual character of the
std::string
using
[]
with
[0]
being the first character.
So
item_type_str[0]
is the first character that the user typed.
There is a standard library function
isalpha()
to test if a character is a letter, rather than a number or a space or a symbol:
So
isalpha(item_type_str[0])
tests the first character the user entered to see if it is a letter "a-z, A-Z" rather than anything else (a digit for example).
If it was a letter then we can simply use it as-is and compare it with known letters
'b'
,
'd'
, etc...
Otherwise, if it was a number, it could be several characters long and needs converting into an integer. To do this conversion I used a
std::istringstream
. By putting what the user entered into a
std::istringstream
I am giving myself another opportunity to read the user input again but this time into an integer, rather than a
std::string
.
std::istringstream(item_type_str)
creates an input stream out of the input a bit like
cin
. We can thus read our integer directly from it like this:
std::istringstream(item_type_str) >> item_type.
That is a short way to do this:
1 2
|
std::istringstream iss(item_type_str); // create an input stream from our string
iss >> item_type; // read our integer from our new input stream.
| |
I hope that makes things a little clearer... ;o)