TXT或CSV到C++映射
TXT or CSV to C++ 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
我不知道它为什么会这么做。
我想我会使用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
相关文章:
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 将函数类成员映射到类本身内部
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 使用std::函数映射对象方法
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++映射分割错误(核心转储)
- 内联映射初始化的动态atexit析构函数崩溃
- 使用"std::unordereded_map"映射到"std::list"对象
- 如何从多映射中删除特定的重复项
- 在未初始化映射的情况下,将值插入到映射的映射中
- QT通过C++添加映射QML项目
- 在c++中访问int到类对象的映射时出错
- 在C++中搜索嵌套多映射值
- 错误处理.将系统错误代码映射到泛型
- C++匿名结构作为std::映射值
- 如何从存储在std::映射中的std::集中删除元素
- 递归无序映射
- 正在VS调试器中监视映射条目