(C++) std::stoi
January 3, 2018 ยท View on GitHub
std::stoi is a C++11 STL function to convert a std::string to int.
Example: input can be converted to integer
#include <cassert>
#include <string>
int main()
{
assert(std::stoi("123") == 123);
}
Example: input is no integer
If the input cannot be converted to integer, a std::invalid_argument is thrown.
#include <cassert>
#include <stdexcept>
#include <string>
int main()
{
try
{
std::stoi("this is no int");
assert(!"Should not get here");
}
catch (const std::invalid_argument&)
{
assert("OK");
}
}
Example: input is a too big integer
If the input is a too big integer, a std::out_of_range is thrown.
#include <cassert>
#include <stdexcept>
#include <string>
int main()
{
try
{
std::stoi("12345678901234567890123456789012345678901234567890");
assert(!"Should not get here");
}
catch (const std::out_of_range&)
{
assert("OK");
}
}
Example: handle both exceptions
#include <cassert>
#include <stdexcept>
#include <string>
int main()
{
try
{
std::stoi("[your string here]");
assert(!"Should not get here");
}
catch (const std::invalid_argument&)
{
assert("OK");
}
catch (const std::out_of_range&)
{
assert("OK");
}
}
As an alternative, the base of both exceptions (called std::exception) can be used:
#include <cassert>
#include <stdexcept>
#include <string>
int main()
{
try
{
std::stoi("[your string here]");
assert(!"Should not get here");
}
catch (const std::exception&)
{
assert("OK");
}
}