I just discovered (much to my surprise) that the following inputs do not cause std::stoi to throw an exception:
3.14
3.14helloworld
Violating the principle of least surprise - since none of these are valid format integer values.
Note, perhaps even more surprisingly 3.8 is converted to the value 3.
Is there a more stringent version of std::stoi which will throw when an input really is not a valid integer? Or do I have to roll my own?
As an asside, why does the C++ standard library implement std::stoi this way? The only practical use this function has is to desperately try and obtain some integer value from random garbage input - which doesn't seem like a very useful function.
This was my workaround.
static int convertToInt(const std::string& value)
{
std::size_t index;
int converted_value{std::stoi(value, &index)};
if(index != value.size())
{
throw std::runtime_error("Bad format input");
}
return converted_value;
}
The answer to your question:
is: No, not in the standard library.
std::stoi, as described here behaves like explained in CPP reference:And if you want a maybe more robust version of
std::stoiwhich fits your special needs, you do really need to write your own function.There are that many potential implementations that there is not the ONE "correct" solution. It depends on your needs and programming style.
I just show you (one of many possible) example solution: