gpt4 book ai didi

c++ - TXT 或 CSV 到 C++ 映射

转载 作者:太空宇宙 更新时间:2023-11-04 14:03:35 24 4
gpt4 key购买 nike

我正在寻找从我拥有的 txt 文件中获取数据并将该数据合并到 C++ map 容器中的最佳/最简单方法。我有一个包含所有无符号整数的二维 txt 文件。如果这样更容易,我也可以将文件重新格式化为 CSV。

这是我尝试导入数据然后打印出来的代码。
代码片段:

 static const int rowamount = 13;

// Store pairs (Time, LeapSeconds)
map<int, int> result;

// Read data from file
ifstream input("Test.txt");
for (int currrow = 1; currrow <= rowamount; currrow++)
{
int timekey;
input >> timekey;

int LeapSecondField;
input >> LeapSecondField;

// Store in the map
result[timekey] = LeapSecondField;
}

for (auto it = result.begin(); it != result.end(); ++it)
{
cout << it->first << endl;
cout << it->second << endl;
}

文件:

173059200 23
252028800 24
315187200 25
346723200 26
393984000 27
425520000 28
457056000 29
504489600 30
551750400 31
599184000 32
820108800 33
914803200 34
1025136000 35

我的输出是这样的:

1606663856
32767

我不确定为什么要这样做。

最佳答案

我想我会使用 istream_iterator 来处理大部分工作,所以结果看起来像这样:

#include <map>
#include <iostream>
#include <iterator>
#include <fstream>

// Technically these aren't allowed, but they work fine with every
// real compiler of which I'm aware.
namespace std {
std::istream &operator>>(std::istream &is, std::pair<int, int> &p) {
return is >> p.first >> p.second;
}

std::ostream &operator<<(std::ostream &os, std::pair<int, int> const &p) {
return os << p.first << "\t" << p.second;
}
}

int main(){
std::ifstream in("test.txt");

std::map<int, int> data{std::istream_iterator<std::pair<int, int>>(in),
std::istream_iterator<std::pair<int, int>>()};

std::copy(data.begin(), data.end(),
std::ostream_iterator < std::pair<int, int>>(std::cout, "\n"));

}

关于c++ - TXT 或 CSV 到 C++ 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18065217/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com