使用substr提取文本文件的麻烦

时间:2018-03-09 10:15:44

标签: c++ c++11

我有方法

double TrainingSession::CalcCalorieBurnGross()
{
  int VO2_max = 48, seconds, H, t1, t2, t3;
  std::string text;
  std::ifstream hrdata("hrdata.txt");
  std::getline(hrdata, text);
  while(std::getline(hrdata, text))
  { // while running through each line of the text
    std::string time = text.substr(4,2);
    std::string time2= text.substr(7,2);
    std::string time3 = text.substr(0,2);
    std::string heart=text.substr(10,3);
    t2 = atoi(time.c_str());
    t1 = atoi(time2.c_str());
    t3 = atoi(time3.c_str());
    H = atoi(heart.c_str());
    Ht+=H;
    next+=cal_m;
    cal_m=((-95.7735+(0.634*Ht)+(0.404*VO2_max)+(0.394*weight)+
    (0.271*age))/4.184)*seconds/60;
    }
    seconds=t3*3600+t2*60+t1;

    return next;
    }

接下来应该从每行的文本中返回等式的所有总和的总和,该值应该是大约1000卡路里,但它是1.79499e-307

未使用最后2个数字 如果需要,我可以发送文本文件给你 编辑:现在的问题是计算同一心跳的时间量,并将每个心跳放在等式中 文本文件样本:

00:00:00,136,101,28.4

00:00:01,136,101,28.4

00:00:02,136,103,28.4

00:00:03,136,103,28.4

00:00:04,136,102,28.4

00:00:05,137,100,28.5

00:00:06,137,101,28.4

00:00:07,138,99,28.5

00:00:08,139,99,28.4

00:00:09,139,99,28.5

2 个答案:

答案 0 :(得分:1)

看看这段代码:

cal_m = some_function_of(H, VO2_max, weight, age, seconds);
cal = cal_m;
next = cal + cal_m;
cal_m = two;

这相当于:

cal_m = some_function_of(H, VO2_max, weight, age, seconds);
next = 2 * cal_m;

所以你从以前的迭代中丢弃 next的值;你总是只保留一行的贡献(尽管加倍)。

答案 1 :(得分:0)

正如rafix07所述,您对substr的使用是错误的,但您可以使用stringstream重写循环,而不是更正它来从字符串中提取数据。< / p>

这将允许您处理子串的长度与预期长度不同的情况。例如,考虑H,如果它代表每分钟的心跳,则可以是3位或2位数字。

所以你可以写:

// ...
#include <sstream>
#include <array>
// ...
std::ifstream hrdata("hrdata.txt");
std::string text;
while( std::getline(hrdata, text) )
{
    std::array<char, 3> del;
    int t0, t1, t2, H;
    if ( text.empty() )
        continue;

    std::istringstream iss {text};
    if ( iss >> t0 >> del[0] >> t1 >> del[1] >> t2 >> del[2] >> H
         and del[0] == ':' and del[1] == ':' and del[2] == ',' )
    {
        int seconds = t1 * 60 + t2;   
        // ...                                                                                        
    }
}