TXT或CSV到C++映射

TXT or CSV to C++ Map

本文关键字:C++ 映射 CSV TXT      更新时间:2023-10-16

我正在寻找最好/最简单的方法,从我拥有的txt文件中获取数据,并将这些数据合并到C++中的映射容器中。我有一个包含所有无符号整数的二维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"));
}

您也可以使用ios:bin标志打开二进制文件,这样您就可以直接在映射中输入/输出值。

在使用数据读取之前,您没有检查读取操作是否成功。

如果>>运算符(在std::basic_ifstream的情况下)调用失败,则该值保持未修改,程序将继续。如果该值以前没有初始化,那么在这种失败之后读取它将导致未定义的行为。

要检查读取操作是否成功,只需检查>>运算符的返回类型:

if (input_stream >> value) {
    std::cout << "Successfully read value: " << value;
} else {
    std::cout << "Failed to read value.";
}

这里有一个简单的解决方案,可以帮助您安全地将文本文件中的数据读取到地图中(文本文件中必须用空格分隔标记)。

std::ifstream input("Test.txt");
std::map<int, int> m;
for (int token1, token2; input >> token1 >> token2;) {
    m[token1] = token2;
}

示例:http://ideone.com/oLG4HN