Robin Chow's C++ Blog

 

[导入]Convert from string to int

The methods: 1) From the C standard library, using atoi:
#include 
#include 
std::string text = "152"; 
int number = std::atoi( text.c_str() ); 
if (errno == ERANGE) //that may be std::errno 
{ 
//the number was too big/small to store completely, number is either LONG_MAX or LONG_MIN 
} 
else if (errno == ????) 
//maybe EINVAL? not sure, man page dosn't seem to say... 
//other possibilities are E2BIG and EDOM (or ERANGE maybe again)... 
//but I'd vote for EINVAL 
{ 
//unable to convert to a number 
}
2) From the C++ standard library, using strstream:
#include 
#include 
std::string text = "152"; 
int number; 
std::istringstream ss( text ); 
ss >> number; 
if (! ss.good()) 
{ 
//something happened 
}
3) From the Boost library, using lexical_cast:
#include 
#include  

try 
{ 
std::string text = "152"; 
int number = boost::lexical_castint >( text ); 
} 
catch( const boost::bad_lexical_cast & ) 
{ 
//unable to convert 
}

文章来源:http://my.donews.com/robinchow/2007/04/17/post-070417-111701-329/

posted on 2007-10-23 20:45 Robin Chow 阅读(372) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理


导航

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜