Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there no std::stou?

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?

like image 992
David Stone Avatar asked Jan 03 '12 16:01

David Stone


People also ask

What library is stoi in C++?

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.

Does stoi work for negative numbers?

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.

What does stoi return if fails?

If no conversion could be performed, zero is returned. The previous reference said that no conversion would be performed, so it must return 0.


2 Answers

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.

like image 169
Kerrek SB Avatar answered Oct 07 '22 03:10

Kerrek SB


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.)

like image 33
Mike Seymour Avatar answered Oct 07 '22 02:10

Mike Seymour