In your code, key
is a C++ string.
string key;
This converts the C++ string to a C string.
key.c_str()
This converts the C string to a number. An integer. (0
if the value can't be converted)
atoi(key.c_str())
And this checks whether that number is the ASCII code for a letter
isalpha(atoi(key.c_str()))
You're converting a C++ string to a C string to an integer to an ASCII value, and then checking whether that value is a letter of the alphabet (which won't tell you if it's a number, only whether it's "a letter" or "not a letter")
The if statement you've written will be true only when the user enters something that is not the numeric ASCII value of a letter. E.g. entering 65
will go to the else clause, because 65
is the ASCII code for 'A'
Try the suggestion @chris kindly offers.
try
{
int the_number = std::stoi(key);
//do something
}
catch( std::exception& )
{
//do something else
}