This is a version close to what @GMan did, but it doesn't accept precedding spaces. e.g. " 101":
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <exception>
long strict_conversion(const std::string& number_string)
{
long number;
std::stringstream convertor;
convertor << std::noskipws << number_string;
convertor >> number;
if( convertor.fail() || !convertor.eof() )
throw std::runtime_error("The string didn't pass the strict conversion!");
return number;
}
After one minute, here is the generic one:
template <typename NumberType>
NumberType strict_conversion(const std::string& number_string)
{
NumberType number;
std::stringstream convertor;
convertor << std::noskipws << number_string;
convertor >> number;
if( convertor.fail() || !convertor.eof() )
throw std::runtime_error("The string didn't pass the strict conversion!");
return number;
}