C++ 增强词汇投射<;int>;检查
这应该很容易。我有一个函数,它遍历csv并基于逗号进行标记化,并使用标记进行操作。其中之一是将其转换为int。不幸的是,第一个标记可能并不总是int,因此当它不是int时,我想将其设置为“5” 目前:C++ 增强词汇投射<;int>;检查,c++,boost,casting,lexical-cast,boost-tokenizer,C++,Boost,Casting,Lexical Cast,Boost Tokenizer,这应该很容易。我有一个函数,它遍历csv并基于逗号进行标记化,并使用标记进行操作。其中之一是将其转换为int。不幸的是,第一个标记可能并不总是int,因此当它不是int时,我想将其设置为“5” 目前: t_tokenizer::iterator beg = tok.begin(); if(*beg! ) // something to check if it is an int... { number =5; } else { number = boost::lexical_
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 );
}
t_标记器::迭代器beg=tok.begin();
if(*beg!)//要检查的内容是否为int。。。
{
数字=5;
}
其他的
{
number=boost::词法转换(*beg);
}
我通常不喜欢以这种方式使用异常,但这对我很有效:
try {
number = boost::lexical_cast<int>(*beg);
} catch (boost::bad_lexical_cast) {
number = 5;
}
试试看{
number=boost::词法转换(*beg);
}捕获(boost::错误的\u词汇\u投射){
数字=5;
}
将失败视为词法转换
抛出
try {
number = boost::lexical_cast<int>(*beg);
}
catch(boost::bad_lexical_cast&) {
number = 5;
}
试试看{
number=boost::词法转换(*beg);
}
捕获(boost::错误的\u词法\u cast&){
数字=5;
}
我很好奇:除了使用boost::optional
之外,您还有什么建议吗?默默地失败?一个意味着它失败的神奇数字?