Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
706 views
in Technique[技术] by (71.8m points)

c++11 - What is the difference between std::atoi() and std::stoi?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...