简体   繁体   中英

the base argument of std::stoi

The stoi function of c++ is defined as:

int stoi(const std::string& str, std::size_t* pos = 0, int base = 10);

as you can see, the base argument is defaulted as 10 , so by default it could only handle decimal numbers. By setting base to 0 , it could handle numbers by their prefixes. This is same behavior as strtol , so why is the default value being set to 10 , rather than 0 ?

I wrote the proposal that added these functions. The goal of the various stoX conversion functions was to provide simple conversions. Base 10 is by far the most common usage, and ought to be the simplest, hence the default. Base 0 would lead to many beginner's questions about why converting the string "010" doesn't produce 10. You can see this if you read enough questions on Stackoverflow -- many beginners are confused about the rules for literal constants, and expect int x = 010; to initialize x to 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM