What is the difference between std::atoi() and std::stoi?

Bhupesh Pant picture Bhupesh Pant · Dec 14, 2013 · Viewed 52.9k times · Source

What is the difference between atoi and stoi?

I know,

std::string my_string = "123456789";

In order to convert that string to an integer, you’d have to do the following:

const char* my_c_string = my_string.c_str(); 
int my_integer = atoi(my_c_string);

C++11 offers a succinct replacement:

std::string my_string = "123456789"; 
int my_integer = std::stoi(my_string);

1). Are there any other differences between the two?

2). Efficiency and performance wise which one is better?

3). Which is safer to use?

Answer

Ali picture Ali · Dec 14, 2013

1). Are there any other differences between the two?

I find std::atoi() a horrible function: It returns zero on error. If you consider zero as a valid input, then you cannot tell whether there was an error during the conversion or the input was zero. That's just bad. See for example How do I tell if the c function atoi failed or if it was a string of zeros?

On the other hand, the corresponding C++ function will throw an exception on error. You can properly distinguish errors from zero as input.

2). Efficiency and performance wise which one is better?

If you don't care about correctness or you know for sure that you won't have zero as input or you consider that an error anyway, then, perhaps the C functions might be faster (probably due to the lack of exception handling). It depends on your compiler, your standard library implementation, your hardware, your input, etc. The best way is to measure it. However, I suspect that the difference, if any, is negligible.

If you need a fast (but ugly C-style) implementation, the most upvoted answer to the How to parse a string to an int in C++? question seems reasonable. However, I would not go with that implementation unless absolutely necessary (mainly because of having to mess with char* and \0 termination).

3). Which is safer to use?

See the first point.

In addition to that, if you need to work with char* and to watch out for \0 termination, you are more likely to make mistakes. std::string is much easier and safer to work with because it will take care of all these stuff.