2013-07-23 23 views
0

lexical_cast在以下情況下引發異常。有沒有辦法使用lexical_cast並將字符串轉換爲整數。詞彙表演部分轉換 - 有可能嗎?

#include <iostream> 
#include "boost/lexical_cast.hpp" 
#include <string> 
int main() 
{ 
     std::string src = "124is"; 
     int iNumber = boost::lexical_cast<int>(src); 
     std::cout << "After conversion " << iNumber << std::endl; 
} 

我明白了,我可以用atoi而不是boost::lexical_cast。 !

+1

'的std :: stoi'一個數字應該這樣做。 – chris

+0

謝謝克里斯。讓我嘗試。 – user373215

+0

你有一些要求阻止你預處理字符串嗎? – shuttle87

回答

1

如果我正確理解您的要求,看起來好像在lexical_cast將解決您的問題之前首先從字符串中刪除非數字元素。我概述這裏的方法利用了ISDIGIT函數將返回true,如果給定char是從0到9

#include <iostream> 
#include "boost/lexical_cast.hpp" 
#include <string> 
#include <algorithm> 
#include <cctype> //for isdigit 

struct is_not_digit{ 
    bool operator()(char a) { return !isdigit(a); } 
}; 

int main() 
{ 
    std::string src = "124is"; 
    src.erase(std::remove_if(src.begin(),src.end(),is_not_digit()),src.end()); 
    int iNumber = boost::lexical_cast<int>(src); 
    std::cout << "After conversion " << iNumber << std::endl; 
} 
+0

非常好。這解決了這個問題。 – user373215

1

升壓/ lexical_cast的使用字符串流從字符串到其它類型的轉換,所以你必須確保該字符串可以完全轉換,或者它會拋出bad_lexical_cast例外,這是一個例子:

#include <boost/lexical_cast.hpp> 

#include <iostream> 

#include <string> 

#define ERROR_LEXICAL_CAST  1 

int main() 

{ 

    using boost::lexical_cast; 

    int   a = 0; 

    double  b = 0.0; 

    std::string s = ""; 

    int   e = 0;  

    try 

    { 

     // ----- string --> int 

     a = lexical_cast<int>("123");//good 

     b = lexical_cast<double>("123.12");//good 


     // -----double to string good 

     s = lexical_cast<std::string>("123456.7"); 

     // ----- bad 

     e = lexical_cast<int>("abc"); 

    } 

    catch(boost::bad_lexical_cast& e) 

    { 

     // bad lexical cast: source type value could not be interpreted as target 

     std::cout << e.what() << std::endl; 

     return ERROR_LEXICAL_CAST; 

    } 



    std::cout << a << std::endl; // cout:123 

    std::cout << b << std::endl; //cout:123.12 

    std::cout << s << std::endl;  //cout:123456.7 

    return 0; 

} 
+0

謝謝。欣賞它。 – user373215

+0

歡迎您!我也不太熟悉boost!我認爲boost值得仔細學習!! go together! – minicaptain