【发布时间】:2017-03-13 07:52:39
【问题描述】:
我正在从 ASCII 文件中以科学计数法读取以空格分隔的单精度值。每行有多个值。我通过流填充向量;向量的原始类型可能与数据的类型不同:
// Illustrates typical string from file
std::string string_with_floats("-2.750000e+001 2.750000e+001 3.450000e+001");
// Template parameter is the desired return type
vector<int> data = ReadValues<int>(string_with_floats);
template <class T>
vector<T>& ReadValues(std::string& string_with_data)
{
std::stringstream ss(string_with_data);
std::vector<T> values;
T val;
while(stream >> val)
{
values.push_back(val);
}
return values;
}
上面的示例导致向量仅填充第一个值,截断为 -2,大概是因为一旦遇到非数字字符,循环就会终止。当传入的字符串包含 int 值时,它会按预期工作,即使模板参数是 float。
有没有办法配置字符串流以执行隐式转换并舍入到最接近的整数,还是我需要先插入原始原始类型(浮点)并执行显式转换为 T?理想情况下,我不想告诉 ReadValues 关于 string_with_data 中数据的类型 - 它始终是 double、float、int、short 或 long 之一,并且请求的类型也可以是这些类型中的任何一种。
谢谢。
【问题讨论】:
标签: c++ implicit-conversion stringstream