有没有可以在 c++ 中替换 atoi 的函数。我做了一些研究并没有找到任何可以替代它的东西,唯一的解决方案是使用 cstdlib 或自己实现它
6 回答
如果您不想使用 Boost,std::stoi
则为字符串添加了 C++11。所有类型都存在类似的方法。
std::string s = "123"
int num = std::stoi(s);
与 不同atoi
的是,如果无法进行转换,invalid_argument
则会引发异常。此外,如果值超出 int 的范围,out_of_range
则会引发异常。
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
}
}
您可以使用 Boost 函数 boost::lexical_cast<> 如下:
char* numericString = "911";
int num = boost::lexical_cast<int>( numericString );
可以在此处找到更多信息(最新的 Boost 版本 1.47)。请记住适当地处理异常。
没有 boost:
stringstream ss(my_string_with_a_number); int my_res; ss >> my_res;
和 boost 版本一样烦人,但没有额外的依赖。可能会浪费更多的内存。
你没有说为什么atoi
不合适,所以我猜它与性能有关。无论如何,澄清会有所帮助。
使用 Boost Spirit.Qi 比使用 Boost Spirit.Qi 快一个数量级atoi
,至少在Alex Ott 所做的测试中是这样。
我没有参考,但我上次测试时,Boostlexical_cast
比atoi
. 我认为原因是它构造了一个字符串流,这非常昂贵。
更新:一些最近的测试
您可以使用该功能stoi();
#include <string>
// Need to include the <string> library to use stoi
int main(){
std::string s = "10";
int n = std::stoi(s);
}
要实际编译它,您必须启用 c++11,在 google 上查找如何操作(在 code::blocks 上是:设置 -> 编译器 -> “让 g++ 遵循 C++11 ISO C++ 语言标准”)如果从终端编译,则必须添加 -std=c++11
g++ -std=c++11 -o program program.cpp