TXT或CSV到C ++地图

时间:2013-08-05 18:32:24

标签: c++ csv text map

我正在寻找从我拥有的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

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

3 个答案:

答案 0 :(得分:0)

我想我会使用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"));

}

答案 1 :(得分:0)

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

如果>>运算符(在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

答案 2 :(得分:0)

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