C++11 added some new string conversion functions:
http://en.cppreference.com/w/cpp/string/basic_string/stoul
It includes stoi (string to int), stol (string to long), stoll (string to long long), stoul (string to unsigned long), stoull (string to unsigned long long). Notable in its absence is a stou (string to unsigned) function. Is there some reason it is not needed but all of the others are?
related: No "sto{short, unsigned short}" functions in C++11?
The stoi() is a standard library function that turns a string into an integer. C++ programmers utilize the function, which stands for “string to integer,” to obtain integers from strings.
How To Use the C++ String to Integer (STOI) Conversion. As this example shows, stoi does not mind the minus sign in string s1, chops off the characters we see after 123 in string s2, and removes all those unsightly zeros for us in string s3.
If no conversion could be performed, zero is returned. The previous reference said that no conversion would be performed, so it must return 0.
The most pat answer would be that the C library has no corresponding “strtou
”, and the C++11 string functions are all just thinly veiled wrappers around the C library functions: The std::sto*
functions mirror strto*
, and the std::to_string
functions use sprintf
.
Edit: As KennyTM points out, both stoi
and stol
use strtol
as the underlying conversion function, but it is still mysterious why while there exists stoul
that uses strtoul
, there is no corresponding stou
.
I've no idea why stoi
exists but not stou
, but the only difference between stoul
and a hypothetical stou
would be a check that the result is in the range of unsigned
:
unsigned stou(std::string const & str, size_t * idx = 0, int base = 10) { unsigned long result = std::stoul(str, idx, base); if (result > std::numeric_limits<unsigned>::max()) { throw std::out_of_range("stou"); } return result; }
(Likewise, stoi
is also similar to stol
, just with a different range check; but since it already exists, there's no need to worry about exactly how to implement it.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With