c++模板将字符串转换为数字
C++ template converting string to number
我有以下模板函数:
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;
}
它不起作用,因为您正在读取的字符串不能转换为数字,因此您返回未初始化的垃圾。发生这种情况是因为你读错了字符串——如果line
是foo bar 345
, keyword
是bar
,那么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;
这样,您可以转换正确的子字符串,并且还可以正确处理不能将其转换为整数的情况。
相关文章:
- 将数字转换为字母(例如:123 转换为一二三)
- 将数字转换为单词
- 使用if-else将数字转换为单词
- 将数字转换为填充字符串
- 函数在许多数字上转换为基数 1 时减去 2?
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何将 UTF-8 文本从文件转换为某个可以迭代的容器,并检查每个符号是否为C++字母数字?
- 将 C 函数转换为 C++ 以检查数字是否有效
- 编译时间文本到数字转换 (atoi)
- 以C++格式将字符串转换为数字
- 在 c++ 中将数字转换为矢量数组的函数
- 奇怪的数字转换C++
- 我想使用 std::stoi 函数在 cpp 中将字符串转换为整数,因为我想在字符串中找到不同数字的总和(在下级酶中)
- 用C++将浮点数字转换为本地化字符串
- 我需要静态转换我的数字模板值吗
- 如何将boost::asio::ip::address_v6 ip转换为2个uint64_t数字,并从2个uint 64
- Rcpp - 用二进制函数转换数字向量?
- 我如何使用堆栈转换数字从基数10到基数2在c++
- 如何在c++中从字节数组中的整数转换数字
- c++程序转换数字的位数