boost lexical cast <int> check

4.1k Views Asked by At

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. One of these things is convert it into an int. Unfortunately, the first token may not always be an int, so when it is not, I'd like to set it to "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 );
}
2

There are 2 best solutions below

0
On BEST ANSWER

Seeing as lexical_cast throws on failure...

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

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;
}