Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

equivalent of atoi

Tags:

c++

atoi

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

like image 863
Mansuro Avatar asked Aug 13 '11 13:08

Mansuro


People also ask

What is the difference between atoi and stoi?

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.

Is atoi C or C++?

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.

What is atoi function?

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.

What is atoi in Java?

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)


2 Answers

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.

like image 149
David Rinck Avatar answered Oct 24 '22 02:10

David Rinck


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        } } 
like image 21
Armen Tsirunyan Avatar answered Oct 24 '22 02:10

Armen Tsirunyan