Is there a function that could replace atoi in c++. I made some research and didn't find anything to replace it, the only solutions would be using cstdlib or implementing it myself
Using atoi() First, atoi() converts C strings (null-terminated character arrays) to an integer, while stoi() converts the C++ string to an integer. Second, the atoi() function will silently fail if the string is not convertible to an int , while the stoi() function will simply throw an exception.
C++ atoi() Function The atoi() function in C++ is defined in the cstdlib header. It accepts a string parameter that contains integer values and converts the passed string to an integer value.
Description. The atoi() function converts a character string to an integer value. The input string is a sequence of characters that can be interpreted as a numeric value of the specified return type. The function stops reading the input string at the first character that it cannot recognize as part of a number.
The atoi() function in C takes a string (which represents an integer) as an argument and returns its value of type int. So basically the function is used to convert a string argument to an integer. Syntax: int atoi(const char strn)
If you don't want to use Boost, C++11 added std::stoi
for strings. Similar methods exist for all types.
std::string s = "123" int num = std::stoi(s);
Unlike atoi
, if no conversion can be made, an invalid_argument
exception is thrown. Also, if the value is out of range for an int, an out_of_range
exception is thrown.
boost::lexical_cast
is your friend
#include <string> #include <boost/lexical_cast.hpp> int main() { std::string s = "123"; try { int i = boost::lexical_cast<int>(s); //i == 123 } catch(const boost::bad_lexical_cast&) { //incorrect format } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With