[英]Reading file starting at a specific line into a vector of pairs
Here is a txt file snippet that I have which lists temperature, voltage, and sensitivity 这是我拥有的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
What I am trying to accomplish is reading the values for Temp and Voltage into a vector of pairs, so that if looked up the Temp, I can find the corresponding Voltage. 我要完成的工作是将“温度”和“电压”的值读入成对的向量中,这样,如果查看“温度”,我可以找到相应的电压。 Would it be easier/more efficient to make two separate vectors and just look up the corresponding value based on its position? 制作两个单独的向量并根据其位置查找相应的值会更容易/更有效吗?
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();
}
Here is the example code, you can change the line number and include conditional execution 这是示例代码,您可以更改行号并包括条件执行
#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;
}
}
If you are not going to use the sensitivity data, you could do something like this: 如果您不打算使用灵敏度数据,则可以执行以下操作:
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;
}
There is an fundamental issue here of using a floating point value as the search key. 这里存在一个基本问题,即使用浮点值作为搜索关键字。 Floating point values, by their internal representation, can't be represented exactly; 浮点值无法通过内部表示精确表示; thus operator==
may not work correctly for all values. 因此, operator==
可能不适用于所有值。
To get around the equality issue, most programs use an equivalence or epsilon to determine equality. 为了解决平等问题,大多数程序使用等价或epsilon来确定平等。 For example, if the difference between two floating point values is less than 1E-6, consider them equal. 例如,如果两个浮点值之间的差小于1E-6,则认为它们相等。 I recommend exploring std::map
to see how to overload the comparison operator (or provide a function for comparing values). 我建议浏览std::map
以了解如何重载比较运算符(或提供用于比较值的函数)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.