2011-07-29 44 views
0

我有以下模板函數:C++模板變換字符串編號

template <typename N> 
    inline N findInText(std::string line, std::string keyword) 
    { 
    keyword += " "; 
    int a_pos = line.find(keyword); 
    if (a_pos != std::string::npos) 
    { 
     std::string actual = line.substr(a_pos,line.length()); 
     N x; 
     std::istringstream (actual) >> x; 
     return x; 
    } 
    else return -1; // Note numbers read from line must be always < 1 and > 0 
    } 

好像行:

std::istringstream (actual) >> x; 

不工作。 但是同樣的功能沒有模板:

int a_pos = line.find("alpha "); 
    if (a_pos != std::string::npos) 
    { 
     std::string actual = line.substr(a_pos,line.length()); 
     int x; 
     std::istringstream (actual) >> x; 
     int alpha = x; 
    } 

作品就好了。 它是一個問題與std :: istringstream和模板?

我正在尋找一種方法來讀取配置文件和加載參數,它們可以是int或real。

編輯解決方案:

template <typename N> 
    inline N findInText(std::string line, std::string keyword) 
    { 
    keyword += " "; 
    int a_pos = line.find(keyword); 
    int len = keyword.length(); 
    if (a_pos != std::string::npos) 
    { 
     std::string actual = line.substr(len,line.length()); 
     N x; 
     std::istringstream (actual) >> x ; 
     return x; 
    } 
    else return -1; 
    } 
+0

你是怎麼調用這個函數的?什麼是'N'?你有編譯錯誤嗎? – interjay

+0

沒有編譯錯誤。我將這個函數稱爲:alpha = var :: findInText (line,「alpha」); –

回答

1

它不工作,因爲你正在閱讀的字符串不能轉換爲數字,所以你返回未初始化的垃圾。發生這種情況是因爲您讀錯了字符串 - 如果linefoo bar 345keywordbar,那麼actual設置爲bar 345,它不會轉換爲整數。你反而想轉換345

你應該重寫你的代碼是這樣的:

std::string actual = line.substr(a_pos + keyword.length()); 
    N x; 
    if (std::istringstream (actual) >> x) 
     return x; 
    else 
     return -1; 

這樣一來,你轉換適當子,你也妥善處理時不能轉換爲整數的情況。

+0

行包含三個關鍵字空格和數字,我只對數字感興趣。 –

+0

其實我需要:int len = keyword.length(); std :: string actual = line.substr(len,line.length()); 但是,謝謝你指出這一點! –