C++ style string to number conversions throw exceptions. Take a look at the following example:
string s = "\t\r\n\f\v";
int i = stoi(s);
Since the string is not a number, the stoi function throws an exception `invalid_argument`.
| Function | Supported Language | Description |
|---|---|---|
str2int |
C/C++ | Converts a string to an integer |
str2uint |
C/C++ | Converts a string to an unsigned integer |
str2l |
C/C++ | Converts a string to a long integer |
str2ul |
C/C++ | Converts a string to an unsigned long integer |
str2ll |
C/C++ | Converts a string to a long long integer |
str2ull |
C/C++ | Converts a string to an unsigned long long integer |
str2f |
C/C++ | Converts a string to a float |
str2d |
C/C++ | Converts a string to a double |
safe_stoi |
C++ | Exception free wrapper for stoi |
safe_stol |
C++ | Exception free wrapper for stol |
safe_stoul |
C++ | Exception free wrapper for stoul |
safe_stoll |
C++ | Exception free wrapper for stoll |
safe_stoull |
C++ | Exception free wrapper for stoull |
safe_stof |
C++ | Exception free wrapper for stof |
safe_stod |
C++ | Exception free wrapper for stod |
Notes about C++ only functions (start with safe_):
- Functions are exception free.
- Return value is either
std::nulloptor the converted value.- If the conversion fails, the return value is
std::nullopt. - If the conversion succeeds, the return value is the converted value.
- If the conversion fails, the return value is
- Function parameters are as follows:
std::optional<> function(const T& str, std::size_t* pos = nullptr, int base = 10)stris the string to convert, can bestd::stringorstd::wstringonlyposif not null, the function also sets the value of idx to the position of the first character in str after the numberbaseis the base of the number, default is 10
Notes about C/C++ only functions (start with str2):
- Functions are exception free and return an error or success code.
- Function parameters are as follows:
str2num_errno function(<intergral_type> *out, const char *s, char** endptr , int base)outPointer to the integeral type to store the result in, ex: int, float, double, etc.sC-style string to convert.endptrPointer to a pointer to the character after the last character of the string. If the conversion was successful, this will point to the character after the last character of the converted integer.baseBase of the number, default is 10.str2num_errnoerror code returned by the function.
Safe conversions for C++
std::string s = "123";
auto i = s2n::safe_stoi(s);
// i == 123 if s is a valid integer
// or i == std::nullopt if s is not a valid integerSafe conversions for C/C++
char s[] = "123";
int i = 0;
if( str2int(&i, s) == STR2NUM_SUCCESS){
// i == 123
};
else{
// Conversion failed, i == 0
};Extended examples are included in the examples directory.