从文件有条件逐行读取 [英] conditional line-by-line reading from file

查看:73
本文介绍了从文件有条件逐行读取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在我有了该代码:

if (minimizator_weighted) {
    while (dataFile >> t >> e >> sigma) { // read data file value by value
        /* some code */
    }
}
else {
    while (dataFile >> t >> e) { // all the same but will not read standard deviation
        /* almost the same code */
    }
}

您可以看到 if 之间的唯一区别 else 流是 while 循环的条件。我想知道是否有可能优化该代码段并重新使用代码?如果我可以写某种形式,那就太好了:

As you can see the only difference between if and else flows is the condition of while loop. I wonder if there any possibility to optimize that snippet and re-use the code? It would be great if I could write some kind of:

while ((minimizator_weighted) ? (dataFile >> t >> e >> sigma) : (dataFile >> t >> e)) { ... }

但我不确定该技巧是否正确...您能建议我一些优化吗?谢谢!

but I don't sure if that trick is correct... Could you advise me some optimizations? Thank you!

编辑
这是完整的代码段

EDIT Here is the full code snippet

if (minimizator_weighted) {
    while (dataFile >> t >> e >> sigma) { // read data file value by value
        data_set::pt point;
        point.t = t;
        point.e = e;
        point.c_vis = 0.0;
        point.c_invis = 0.0;

        if (std::abs(sigma) <= GSL_SQRT_DBL_MIN) // check for division-by-zero error
            sigma = 1.0;

        point.sigma = sigma;

        set.curve.push_back(point); // store point

        data_numPoints++; // collect some stats
        set.curveAvg += e;
    }   
}   
else {
    while (dataFile >> t >> e) { // all the same but will not read standard deviation
        data_set::pt point;
        point.t = t;
        point.e = e;
        point.c_vis = 0.0;
        point.c_invis = 0.0;

        set.curve.push_back(point);

        data_numPoints++;
        set.curveAvg += e;
    }   
}


推荐答案

添加间接级别

bool read_data_line1(istream& dataFile, T& t, E& e, Sig& sigma)
{ return dataFile >> t >> e >> sigma; }

bool read_data_line2(istream& dataFile, T& t, E& e, Sig&)
{ return dataFile >> t >> e; }

auto read_data_line_func = minimizator_weighted ? read_data_line1 : read_data_line2;
while(read_data_line_func(dataFile, t, e, sigma))
{
    data_set::pt point;
    point.t = t;
    point.e = e;
    point.c_vis = 0.0;
    point.c_invis = 0.0;

    if (minimizator_weighted)
    {
      if (std::abs(sigma) <= GSL_SQRT_DBL_MIN) // check for division-by-zero error
        sigma = 1.0;
      point.sigma = sigma;
    }

    set.curve.push_back(point); // store point

    data_numPoints++; // collect some stats
    set.curveAvg += e;
}

这篇关于从文件有条件逐行读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆