简体   繁体   English

促进词法转换 <int> 校验

[英]boost lexical cast <int> check

This should be an easy one. 这应该很简单。 I have a function that traverses a csv and tokenizes based on commas and does things with the tokens. 我有一个遍历csv并基于逗号对标记化并使用标记处理功能的函数。 One of these things is convert it into an int. 其中之一是将其转换为int。 Unfortunately, the first token may not always be an int, so when it is not, I'd like to set it to "5". 不幸的是,第一个令牌可能并不总是int,因此当它不是整数时,我想将其设置为“ 5”。

Currently: 目前:

t_tokenizer::iterator beg = tok.begin();
if(*beg! )   // something to check if it is an int...
{
    number =5;
}
else
{
    number = boost::lexical_cast<int>( *beg );
}

Seeing as lexical_cast throws on failure... 看到lexical_cast引发失败...

try {
    number = boost::lexical_cast<int>(*beg);
}
catch(boost::bad_lexical_cast&) {
    number = 5;
}

I don't normally like to use exceptions this way, but this has worked for me: 我通常不喜欢以这种方式使用异常,但这对我有用:

try {
    number = boost::lexical_cast<int>(*beg);
} catch (boost::bad_lexical_cast) {
    number = 5;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM