2013-04-08 57 views
0

我将一个布尔矩阵(ROW * ROW)保存为.txt文件(0,1格式)。如何读取文件

如何从文件中读取矩阵?我在下面写了代码,但是我将读取结果与文件进行比较,并且数组结果与文件不匹配。有人能告诉我我写错了吗?或者有没有更简单的方法来读取矩阵文件?

bool **results = new bool*[ROW]; 
    for(int i=0;i<ROW;i++){ 
     results[i] = new bool[ROW]; 
    } 

    ifstream infile; 
    infile.open ("FRM.txt"); 
    string line; 
    int row=0; 
    if (infile.is_open()) 
    { 
     while (infile.good()) 
     { 
      getline(infile,line); 
      istringstream iss(line); 
      int col=0; 
      while(iss) 
      { 
       string word; 
       iss >> word; 
       int number = atoi(word.c_str()); 
       if(number==1){ 
        results[row][col] = true; 
       } 
       else{ 
        results[row][col] = false; 
       } 
       col++; 
      } 
      row++; 
     } 
    } 
    infile.close(); 
+0

请的std ::法院字。 – 2013-04-08 06:12:28

+0

我知道问题所在。当我保存矩阵时,每个数字后面都有一个空格。所以当我读一行时,我得到了类似“0 1 1 1”的内容,最后一个空格导致了错误。因为“字符串”实际上会处理“”,并将其视为整数0. – 2013-04-08 06:26:36

回答

1

将矩阵表示为嵌套数组通常是一个坏主意。改为使用线性数组,并通过宏或内联函数执行索引 - 杂耍。

我会去这样的事情:

#include <algorithm> 
#include <cmath> 
#include <cstdint> // uint8_t requires C++11 
#include <iterator> 
#include <vector> 

// don't use vector<bool>, it creates all sorts of problems 
std::vector<uint8_t> results; 
{ 
    std::ifstream infile('FRM.txt', std::ifstream::in); 
    if(infile.is_open() && infile.good()) 
    { 
    std::istream_iterator<uint8_t> first(infile), last; 
    copy(first, last, std::back_inserter(results)); 
    } 
} 

// only if you know the matrix is square! error checking strongly advised! 
size_t nrows = size_t(std::sqrt(results.size())); 

// accessing element (i,j) is then as easy as 
size_t i = 2, j = 3; // assuming nrows > i,j 
bool a_ij = results[i*rows+j]; 
+0

这是一个很好的解决方案,但我担心它远离OP有用。 – 2013-04-08 06:21:06

+1

我相信不应该简单地为破坏的代码提供最简单的修复程序...... OP的代码清楚地表明C++不是他/她最强烈的一点,因此可以从更好的示例中获益。 – 2013-04-08 06:26:16

+0

当我使用matlab时,我可以简单地将矩阵保存为.mat文件。所以我想知道,是否有更好的方法来保存矩阵,并读取矩阵。 – 2013-04-08 06:28:06