2011-07-29 41 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()); 但是,谢谢你指出这一点! –