本文介绍了std :: atoi()和std :: stoi有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

atoi stoi 有什么区别?

我知道,

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提供了简洁的替代方法:

C++11 offers a succinct replacement:

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

1)。两者之间还有其他区别吗?

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

2)。在效率和性能方面,哪一个更好?

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

3)。

推荐答案

我发现 std :: atoi()一个可怕的函数:错误返回零。如果您将零视为有效输入,则无法确定转换过程中是否存在错误或输入为零。那太糟糕了。例如,请参见

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?

另一方面,相应的C ++函数将在出错时引发异常。您可以正确区分错误和零作为输入。

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

如果您不关心正确性,或者您确定自己不会输入零或您仍然认为错误,那么C函数可能会更快(可能是由于缺少异常处理)。它取决于您的编译器,您的标准库实现,您的硬件,您的输入等。最好的方法是对其进行度量。但是,我怀疑这种差异(如果有的话)可以忽略不计。

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.

如果您需要快速(但丑陋的C风格)实现,请 //stackoverflow.com/a/6154614/341970> int in C ++?这个问题似乎很合理。但是,除非绝对必要,否则我不会采用该实现(主要是因为必须弄乱 char * \0 终止。)

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

请参阅第一点。

在除此之外,如果您需要使用 char * 并注意 \0 的终止,您将更容易犯错误。 std :: string 使用起来更容易,更安全,因为它将处理所有这些事情。

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.

这篇关于std :: atoi()和std :: stoi有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 17:26