使用 substr 提取文本文件时出现问题

Trouble with text file extracting using substr

本文关键字:问题 文件 substr 提取 取文本 使用      更新时间:2023-10-16

我有方法

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

看看这段代码:

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的值;您始终只保留一行的贡献(尽管翻了一番(。

正如 rafix07 所指出的,你对substr的使用是错误的,但你可以使用stringstream重写循环,而不是纠正它,从字符串中提取数据。

这将允许您处理子字符串长度与预期长度不同的情况。考虑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;   
        // ...                                                                                        
    }
}