2011-04-08 93 views
1

這會導致由於額外的空格問題:問題的boost ::詞彙投

std::string t("3.14 "); 
double d = boost::lexical_cast<double> (t); 

所以,我寫了這個

template<typename T> 
T string_convert(const std::string& given) 
{ 
    T output; 
    std::stringstream(given) >> output; 
    return output; 
} 

double d = string_convert<double> (t); 

什麼可以是這個問題?有沒有更好的辦法?更喜歡使用詞法轉換

回答

6

請注意,您的代碼並不總是正確的。例如,如果您執行string_convert<double>("a"),讀取操作將失敗,並且您將返回output未初始化,導致未定義的行爲。

你可以這樣做:

template<typename T> 
T string_convert(const std::string& given) 
{ 
    T output; 
    if (!(std::stringstream(given) >> output)) 
    throw std::invalid_argument(); // check that extraction succeeded 

    return output; 
} 

注意上面的代碼和Boost的之間的唯一區別是,升壓還進行檢查,以確保沒有流中離開。你應該做的,雖然只是修剪字符串第一:

#include <boost/algorithm/string/trim.hpp> 

std::string t("3.14 "); 
boost::algorithm::trim(t); // get rid of surrounding whitespace 

double d = boost::lexical_cast<double>(t); 
+0

重要的是,上面的'string_convert'模板不只是方便忽略空格:如果還忽略尾隨非空白,可能也預示無效值。 'trim'確實更健壯,或者你可以改變'string_convert' ala'char c; std :: stringstream ss(given); if(!(ss >> output)||(ss >> c))...'。 – 2011-04-08 05:44:16

+0

如果你想要一個忽略尾隨空格的轉換函數,你應該這樣做:'std :: stringstream(given); if(!(s >> output >> ws)|| s.get()!= EOF)throw ...' – 2011-04-08 09:41:00

3

Boost::lexical_cast認爲嘗試轉換成功只有如果整個輸入轉換爲輸出。也就是說,它基本上和你的string_convert一樣,除了在return output之前,它檢查stringstream是否還有任何東西,如果有的話,它認爲轉換「失敗」並拋出異常。