从特定行开始将文件读取到对向量中

Reading file starting at a specific line into a vector of pairs

本文关键字:读取 向量 文件 开始      更新时间:2023-10-16

这是我有一个txt文件片段,其中列出了温度,电压和灵敏度

Temp.      Voltage    Sensitivity
(Kelvin)   (Volts)    (milliVolts/Kelvin)
1.4     1.644290        -12.5
1.5     1.642990        -13.6
1.6     1.641570        -14.8
1.7     1.640030        -16.0
1.8     1.638370        -17.1

试图完成的是将温度和电压的值读取到成对向量中,这样如果查找温度,我可以找到相应的电压。制作两个单独的向量并根据其位置查找相应的值会更容易/更有效吗?

void Convert::readFile()
{
    ifstream inFile;
    vector<double> temp,voltage;
    double kelvin,mV;
    inFile.open("DT-670.txt");
    if (inFile) {
        cout << "File Open";
        while(inFile>>kelvin && inFile>> mV)
        {
            temp.push_back(kelvin);
            voltage.push_back(mV);
        }
        cout<<temp.size();
    }

这是示例代码,您可以更改行号并包含条件执行

#include <fstream>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
int main() {
  ifstream file("data.txt");
  string str = "";
  string::size_type sz;
  uint32_t line_number = 4;
  while (std::getline(file, str)) {
    cout << str << endl;
    istringstream buf(str);
    istream_iterator<string> beg(buf), end;
    vector<string> tokens(beg, end);
    for (auto &s : tokens)
      cout << atof(s.c_str()) << " " << flush;
    cout << endl;
  }
}

如果不打算使用敏感度数据,可以执行以下操作:

std::map<double, double> table;
//...
double temperature = 0.0;
double voltage = 0.0;
double sensitivity = 0.0;
while (file >> temperature >> voltage >> sensitivity)
{
  table[temp] = voltage;
}

这里有一个使用浮点值作为搜索键的基本问题。 浮点值通过其内部表示形式无法准确表示;因此operator==可能无法对所有值正常工作。

为了解决平等问题,大多数程序使用等价或ε来确定平等。 例如,如果两个浮点值之间的差值小于 1E-6,则认为它们相等。 我建议探索std::map以查看如何重载比较运算符(或提供用于比较值的函数)。