2013-08-05 54 views
0

我正在寻找最好的/最简单的方法从txt文件中获取数据并将这些数据合并到C++的映射容器中。我有一个二维txt文件与所有无符号整数整数。如果这会更容易,我也可以将文件重新格式化为CSV。TXT或CSV到C++映射

这里是我尝试导入数据然后打印出来的代码。
代码片段:

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 

我不知道为什么会这样。

+1

您确定您使用的是正确的输入文件吗? – P0W

+0

是的,我是。在这个程序中,我在桌面上创建一个名为LeapList.txt的文件,然后访问同一个文件。 – raoul

+2

你可以在for循环之前检查'std :: cout << input.good()<< std :: endl;'吗? – P0W

回答

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")); 

} 
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

0

你也可以使用的ios ::彬标志打开文件的二进制,这样一来就可以直接输入/输出值到您的地图/。

+0

这里是源:http://bytes.com/topic/net/answers/284533-working-binary-files-c 或者: http://stackoverflow.com/questions/12935078/output- A-stdmap到一个二进制文件 –