Why are stoi, stol not fixed width integers?

Since ints and longs and other integer types can be of different sizes on different systems, why not write stouint8_t()

, stoint64_t()

etc., so that you can write a portable string to int code?

+3


source to share


2 answers


Because it usually isn't necessary.

stoll

and stoull

return results of type long long

and, unsigned long long

respectively. If you want to convert a string to int64_t

, you can simply call stoll()

and store the result in an object int64_t

; the value will be implicitly converted.

It is assumed to be long long

the widest type of signed integer. Like C (since C99), C ++ allows extended integer types, some of which can be broader than [unsigned] long long

. C provides conversion functions strtoimax

and strtoumax

(works on intmax_t

and uintmax_t

, respectively) in <inttypes.h>

. For some reason, C ++ does not provide wrappers for these functions (boolean names would be stoimax

and stoumax

.



But it won't matter unless you use a C ++ compiler that provides an extended integer type wider than [unsigned] long long

that, and I don't know that such compilers actually exist. For any type no more than 64 bits, the existing functions are all you need.

For example:

#include <iostream>
#include <string>
#include <cstdint>

int main() {
    const char *s = "0xdeadbeeffeedface";
    uint64_t u = std::stoull(s, NULL, 0);
    std::cout << u << "\n";

}

      

+5


source


Because typing to make me want to chop off my fingers.

Seriously, basic integer types are int

and long

, and functions std::stoX

are very simple wrappers around strtol

, etc., and note that C does not provide strtoi32

or strtoi64

or anything that std::stouint32_t

can wrap.

If you need something a little more complex, you can write it yourself.



I could just ask: "Why do people use int

and long

, instead int32_t

, and int64_t

everywhere, so the code is transferred?" and the answer would be because it is not always necessary.

But the actual reason is probably that no one has ever proposed it for the standard. The standard is not just magical, someone has to write a proposal and justify its addition, and also convince the rest of the committee to add them. So the answer to most is "why isn't this the thing I just thought of in the standard?" that no one suggested it.

+7


source







All Articles