Dav*_*nck 18
如果您不想使用Boost,std::stoi
则为字符串添加C++ 11 .所有类型都存在类似的方法.
std::string s = "123"
int num = std::stoi(s);
Run Code Online (Sandbox Code Playgroud)
atoi
与之不同,如果不能进行转换,invalid_argument
则抛出异常.此外,如果值超出int的范围,out_of_range
则抛出异常.
Arm*_*yan 10
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
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用Boost函数boost :: lexical_cast <>,如下所示:
char* numericString = "911";
int num = boost::lexical_cast<int>( numericString );
Run Code Online (Sandbox Code Playgroud)
在此处可以找到更多信息(最新的Boost版本1.47)。记住要适当地处理异常。
归档时间: |
|
查看次数: |
23691 次 |
最近记录: |