Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 634
fluter Avatar asked Sep 04 '19 14:09

fluter


People also ask

What is stoi () in C++?

What Is stoi() in C++? In C++, the stoi() function converts a string to an integer value. The function is shorthand for “string to integer,” and C++ programmers use it to parse integers out of strings.

How does STD stoi work?

std::stoi Function 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. Additionally, the stoi() function can remove other components, such as trailing letters from the string.

Where is stoi defined C++?

std::stoi is actually declared in <string> . Also, it was introduced in C++11, so that might be the problem. Don't mix C and C++ headers; use <cstdlib> instead. std::stoi is a standard library function, not a keyword.

What does stoi return?

Since stoi returns the integer value if parsed you can't directly use the return value to check for correctness. You could catch std::invalid_argument exception but it could be too much.


1 Answers

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.

like image 158
Pete Becker Avatar answered Sep 20 '22 12:09

Pete Becker