Lex*_*con 0 c++ boost vector tokenize atof
我正在逐行读取CSV并标记每个逗号分隔值.每个标记都是字符串类型.我把它放入float类型的向量中.在下面的例子中,例如,如果csv中的值是"0.08",*beg ="0.08",但是在向量v中它是"0.079999998"
有没有我可以将矢量的精度设置为3位小数或其他东西.
例:
string line;
boost::char_separator<char> sep(",");
typedef boost::tokenizer< boost::char_separator<char> > t_tokenizer;
ifstream myfile (fileName);
if(myfile.is_open())
{
while (myfile.good())
{
getline (myfile,line);
t_tokenizer tok(line, sep);
for (t_tokenizer::iterator beg = tok.begin(); beg != tok.end(); ++beg)
{
string temp = *beg;
this->v.push_back(::atof(temp.c_str()));
}
Run Code Online (Sandbox Code Playgroud)
这不是float的问题.你不能完全代表0.8,但不用担心 - 只需输出具有所需精度的值:
#include <iomanip> // for fixed and setprecision
#include <iostream> // for cout
#include <cstdio> // for printf
for (auto it = v.cbegin(), end = v.cend(); it != end; ++it)
{
std::cout << std::fixed << std::setprecision(3) << *it << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用std::printf("%.3f\n", *it).
如果您确实想在数据结构中存储确切的值,则不能使用常规浮点数.您可以使用某种整数的定点解释(例如,以1/1000为单位测量所有内容),也可以使用十进制浮点数(稀有),或者可以存储有理数(整数的商).如果你只做加法和减法,定点将是自然的方式.