Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/126.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 增强词汇投射<;int>;检查_C++_Boost_Casting_Lexical Cast_Boost Tokenizer - Fatal编程技术网

C++ 增强词汇投射<;int>;检查

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_

这应该很容易。我有一个函数,它遍历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_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
之外,您还有什么建议吗?默默地失败?一个意味着它失败的神奇数字?