相当于atoi

新手上路,请多包涵

有没有可以在 c++ 中替换 atoi 的函数。我做了一些研究并没有找到任何可以替代它的东西,唯一的解决方案是使用 cstdlib 或自己实现它

原文由 Mansuro 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 841
2 个回答

如果您不想使用 Boost,C++11 为字符串添加了 std::stoi 。所有类型都存在类似的方法。

 std::string s = "123"
int num = std::stoi(s);

atoi 不同,如果无法进行转换,则会抛出 invalid_argument 异常。此外,如果值超出 int 的范围,则会引发 out_of_range 异常。

原文由 David Rinck 发布,翻译遵循 CC BY-SA 3.0 许可协议

boost::lexical_cast 是你的朋友

#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
    }
}

原文由 Armen Tsirunyan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题