the base argument of std::stoi
Asked Answered
H

1

8

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?

Hasseman answered 4/9, 2019 at 14:0 Comment(1)
Possibly because by default they wanted stoi("000123456") to yield a decimal number (just trim the leading zeros) instead of making it an octal value with the leading zeros trimmed off.Makebelieve
F
15

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.

Fai answered 4/9, 2019 at 14:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.