2013-07-22 117 views

回答

1

您可以將字符串拆分爲.,並將其直接轉換爲整數類型。在while循環的第二個數字是你想要的,見示例代碼:

template<typename T> 
T stringToDecimal(const string& s) 
{ 
    T t = T(); 
    std::stringstream ss(s); 
    ss >> t; 
    return t; 
} 

int func() 
{  
    string s("100.3-name"); 

    std::vector<int> v; 
    std::stringstream ss(s); 
    string line; 

    while(std::getline(ss, line, '.')) 
    { 
     v.push_back(stringToDecimal<int>(line)); 
    } 

    std::cout << v.back() << std::endl; 

} 

這將輸出:3

+0

@ billz:你能解釋一下ss >> t嗎? –

+0

'ss >> t'將字符串(可以是'100'或'3-name')轉換爲t,它只寫整數類型並截斷不相關的字符串。就像atoi函數一樣。請參閱http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt – billz

0

使用兩次調用unsigned long strtoul(const char *str, char **str_end, int base),如:

#include <cstdlib> 
#include <iostream> 

using namespace std; 

int main(){ 

    char const * s = "1.99-name"; 
    char *endp; 
    unsigned long l1 = strtoul(s,&endp,10); 
    if (endp == s || *endp != '.') { 
     cerr << "Bad parse" << endl; 
     return EXIT_FAILURE; 
    } 
    s = endp + 1; 
    unsigned long l2 = strtoul(s,&endp,10); 
    if (endp == s || *endp != '-') { 
     cerr << "Bad parse" << endl; 
     return EXIT_FAILURE; 
    } 
    cout << "num 1 = " << l1 << "; num 2 = " << l2 << endl; 
    return EXIT_FAILURE; 
} 
0

你可以用boost::lexical_cast實現它,它利用溪流像billz」回答: 僞代碼是這樣的(指數可能是錯在那個例子):

std::string yxString = "56.74-name"; 
size_t xStart = yxString.find(".") + 1; 
size_t xLength = yxString.find("-") - xStart; 
int x = boost::lexical_cast<int>(yxString + xStart, xLength); 

解析錯誤可以通過由lexical_cast的拋出的異常處理。 爲了更靈活/強大的文本匹配,我建議boost::regex