【问题标题】:TXT or CSV to C++ MapTXT 或 CSV 到 C++ 映射
【发布时间】:2013-08-05 18:32:23
【问题描述】:

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

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

 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

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

【问题讨论】:

  • 你确定你使用的是正确的输入文件吗?
  • 是的,我是。在这个程序中,我在桌面上创建了一个名为 LeapList.txt 的文件,然后我访问了同一个文件。
  • 你能在 for 循环之前检查 std::cout&lt;&lt;input.good()&lt;&lt;std::endl; 吗?
  • 当我编译它并针对具有您指定的 exakt 内容的文本文件运行它时,您的代码工作得很好。但是,在使用任何数据之前,您应该始终检查您的读取操作是否成功。

标签: c++ csv text map


【解决方案1】:

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

}

【讨论】:

    【解决方案2】:

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

    【解决方案3】:

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

    如果&gt;&gt; 运算符(在您的情况下为std::basic_ifstream)调用失败,则该值保持未修改,程序继续。如果该值之前未初始化,则在此类失败后读取它将导致未定义的行为。

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

    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

    【讨论】:

      猜你喜欢
      • 2012-08-29
      • 1970-01-01
      • 2012-04-07
      • 2010-10-05
      • 1970-01-01
      • 1970-01-01
      • 2019-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多