使用 substr 提取文本文件时出现问题
Trouble with text file extracting using substr
我有方法
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;
// ...
}
}
相关文章:
- 使用mongocxx驱动程序时包含头文件问题
- 在WSL:configure_file上对config_file的每次调用都失败:配置文件时出现问题
- 编译要在英特尔Hyperscan中使用的.cc文件时出现问题
- 使用 seekg() 读取C++中的文件时出现问题
- sqlite3 和生成文件中的链接出现问题
- C++头文件和类实现出现问题
- 用户输入字符串的文件附加问题..C++
- node-gyp 的先有鸡还是先有蛋的问题:指向依赖项中的头文件
- 读取文件并将其存储在unordered_map中时出现问题
- 编译 llvm 插件时出现问题:llvm/Config/llvm-config.h:没有这样的文件或目录
- 我在使用C++文件时遇到了一些问题
- 在Linux上使用Clang / OLLVM交叉编译helloworld Windows可执行文件时的问题
- 将文件复制到自定义位置,存在字符串转换问题
- DirectX12 的问题:"d3dApp.h":没有这样的文件或目录
- (ODR 使用问题)在不同文件中priority_queue名称相同的结构
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- 读取制表符分隔的文件时出现问题 C++
- 当我在 CLion 中读取数组中的 txt 文件时C++编码问题
- 使用 RapidXML 解析大型 XML(大小大于 65 KB)文件时出现问题
- C++:读取.BMP文件时出现问题;文件结束时间早于预期