【发布时间】: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<<input.good()<<std::endl;吗? -
当我编译它并针对具有您指定的 exakt 内容的文本文件运行它时,您的代码工作得很好。但是,在使用任何数据之前,您应该始终检查您的读取操作是否成功。