从特定行开始将文件读取到对向量中
Reading file starting at a specific line into a vector of pairs
这是我有一个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
以查看如何重载比较运算符(或提供用于比较值的函数)。
相关文章:
- C++:如何读取分离变量,然后读取向量
- C++读取行到类向量
- 如何从文件中读取两个字符串和数字数组,并将它们存储在对象向量中
- 从流到邻接列表的向量读取图形
- 尝试将字符串从文件读取到无符号字符向量中
- 如何在 c++ 中从字符串向量中读取
- 将结构向量保存到文件中,并从C++文件中读取结构向量
- C++,从文件读取到结构,然后读取到向量(结构被推入向量太多次,而不仅仅是一次)
- 从.txt文件读取到C++中的双精度向量
- 用rapidjson读取子对象向量
- 对唯一 ptr 无效读取的引用向量
- 如何从输入文件中读取字符并将其存储到向量中?
- 如何使用 cin 将整数从控制台读取到向量中
- 无法使用迭代器在类对象的向量中读取向量
- 提升ASIO写入/读取向量
- 试图从文本文件中读取向量
- 我可以读取向量<string>::迭代器的数字位置吗?
- 重载 C++ 运算符>>,以便我可以读取向量(向量<int>向量;
- 按值与按引用读取C++向量
- 从文件中读取向量、结构和While循环