相当于阿托伊
C++中有没有可以替代atoi的函数? 我做了一些研究,但没有找到任何可以替代它的东西,唯一的解决方案是使用 cstdlib 或自己实现它
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果你不想使用Boost,C++11添加了
std::stoi
对于字符串。所有类型都存在类似的方法。与
atoi
不同,如果无法进行转换,则会出现invalid_argument
抛出异常。此外,如果该值超出 int 的范围,则会出现out_of_range
抛出异常。If you don't want to use Boost, C++11 added
std::stoi
for strings. Similar methods exist for all types.Unlike
atoi
, if no conversion can be made, aninvalid_argument
exception is thrown. Also, if the value is out of range for an int, anout_of_range
exception is thrown.boost::lexical_cast
是你的朋友boost::lexical_cast
is your friend您可以使用Boost函数boost::lexical_cast<>如下:
更多信息可以在此处找到(最新升压版本1.47)。请记住适当地处理异常。
You can use the Boost function boost::lexical_cast<> as follows:
More information can be found here (latest Boost version 1.47). Remember to handle exceptions appropriately.
没有升压:
stringstream ss(my_string_with_a_number); int my_res; SS>> my_res;
与 boost 版本一样烦人,但没有添加依赖项。可能会浪费更多的内存。
Without boost:
stringstream ss(my_string_with_a_number); int my_res; ss >> my_res;
About as annoying as the boost version but without the added dependency. Could possibly waste more ram.
您没有说为什么
atoi
不合适,所以我猜测它与性能有关。无论如何,澄清会有所帮助。使用 Boost Spirit.Qi 比 atoi 快一个数量级,至少在 由 Alex Ott 完成的测试。
我没有参考资料,但上次测试时,Boost
lexical_cast
比atoi
慢了大约一个数量级。我认为原因是它构造了一个字符串流,这是相当昂贵的。更新:一些最近的测试
You don't say why
atoi
is unsuitable so I am going to guess it has something to do with performance. Anyway, clarification would be helpful.Using Boost Spirit.Qi is about an order of magnitude faster than
atoi
, at least in tests done by Alex Ott.I don't have a reference but the last time I tested it, Boost
lexical_cast
was about an order of magnitude slower thanatoi
. I think the reason is that it constructs a stringstream, which is quite expensive.Update: Some more recent tests