【问题标题】:Reading file starting at a specific line into a vector of pairs将从特定行开始的文件读入成对向量
【发布时间】:2019-05-31 23:58:00
【问题描述】:

这是我拥有的一个 txt 文件 sn-p,其中列出了温度、电压和灵敏度

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

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

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();

    }

【问题讨论】:

  • 听起来你需要 map 一个值到另一个值...
  • 您的标题与您的问题不符
  • 您不同步,因为您没有阅读Sensitivity。你需要阅读它;但您可以忽略该值(不使用它)。
  • 在互联网上搜索“C++ 比较浮点相等性”。映射和搜索需要比较是否相等。

标签: c++ vector ifstream getline


【解决方案1】:

如果你不打算使用敏感度数据,你可以这样做:

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== 可能不适用于所有值。

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

【讨论】:

    【解决方案2】:

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

    #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;
      }
    }
    

    【讨论】:

    • 不仅仅是转储代码,解释您的解决方案。
    • 另外,这是一种非常低效的标记行的方法。
    • 另外,如果您已经将所有内容都放在了字符串流中,为什么还要使用atof
    • 另外,为什么要冲洗?
    • 另外,空格字符就是这样 - 一个字符。所以," " 可以是' '
    猜你喜欢
    • 2017-04-11
    • 2012-10-30
    • 1970-01-01
    • 2016-12-18
    • 2016-09-16
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多