C++ C++;将字符串转换为数字的模板
我有以下模板功能:C++ C++;将字符串转换为数字的模板,c++,templates,C++,Templates,我有以下模板功能: 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,li
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
}
不起作用。
但是,未模板化相同的函数:
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;
}
模板
内联N findInText(std::string行,std::string关键字)
{
关键词+=“”;
int a_pos=line.find(关键字);
int len=关键字.length();
if(a_pos!=std::string::npos)
{
std::string actual=line.substr(len,line.length());
nx;
标准::istringstream(实际)>>x;
返回x;
}
否则返回-1;
}
它不起作用,因为您正在读取的字符串无法转换为数字,因此您返回的是未初始化的垃圾。这是因为您读取的字符串错误——如果行
是foo bar 345
,而关键字
是bar
,则实际
设置为bar 345
,不会转换为整数。而是要转换345
您应该像这样重写代码:
std::string actual = line.substr(a_pos + keyword.length());
N x;
if (std::istringstream (actual) >> x)
return x;
else
return -1;
这样,您就可以转换正确的子字符串,并且还可以正确处理无法转换为整数的情况。如何调用该函数?什么是
N
?有编译错误吗?没有编译错误。我这样调用函数:alpha=var::findInText(第行,“alpha”);行包含三个元素:关键字、空格和数字,我只对数字感兴趣;std::string actual=line.substr(len,line.length());但谢谢你指出这一点!
std::string actual = line.substr(a_pos + keyword.length());
N x;
if (std::istringstream (actual) >> x)
return x;
else
return -1;