2011-12-03 22 views
2

這應該是一個容易的。我有一個遍歷csv並基於逗號進行標記的函數,並用這個標記進行操作。其中一件事是將其轉換爲int。不幸的是,第一個標記可能並不總是一個int,所以當它不是時,我想將它設置爲「5」。助推詞法鑄<int>查詢

目前:

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

回答

4

看到,因爲lexical_cast拋出失敗...

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

我通常不喜歡使用異常這種方式,但是這很適合我:

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

我很好奇:除了'boost :: optional'的使用,除了異常,你還會有什麼建議嗎?沉默失敗?一個幻數,意味着它失敗了? –