I'm trying to get a number from the user using std::string and want to check first if that string is empty and it contains only numbers, and then check if the number there is higher than zero
When I build it and just press enter I get an exception unhandled of invalid argument at the stoi function.
I try it in an older version of VS (2012), and get the same error.
Does short circuit evaluation works on VS?
static const bool is_number(const char caracter)
{
return(caracter >= '0' && caracter <= '9');
}
template <typename T> static const bool all_numbers(const T &str)
{
if (!str.empty())
{
auto it = str.cbegin();
if ((str.front() == '+' || str.front() == '-') && (str.size()>1)) ++it;
for (it; it != str.cend(); ++it) if (!is_number(*it)) return false;
return true;
}
else return false;
}
int main()
{
std::string str;
do
{
std::cout << " Number: ";
getline(std::cin, str);
std::cin.clear();
}while (!all_numbers(str) && std::stoi(str) <= 0);
return 0;
}
Of course short-circuiting works in Visual Studio, and you could easily have verified this for yourself.
However, your logic is wrong:
(!all_numbers(str) && std::stoi(str) <= 0);
Here you're only performing stoi
if the input isn't all numbers. That is clearly backwards.
I think maybe you meant to write ||
instead?