2012-09-18 28 views
2

好的,我正在经历一些编程练习,并且遇到涉及读取文件的问题。我需要做的是将一组线条读入二维数组中,线条的长度和线条的数量会有所不同,但我事先知道它。用C++将某些行读入二维数组中

所以文件的格式是这样的:

有两个数字,nm,其中1 <= n, m <= 20

现在nm来格式化,像这样的文件:n m(这两个数字之间有一个空格)

现在在该行之后有n每行有m个元素的整数行。因此,例如,一个输入是像这样:(的数字是在的范围内)0 <= # <= 50

5 3 
2 2 15 
6 3 12 
7 3 2 
2 3 5 
3 6 2 

所以从这个程序知道有15种元素,并且可以在阵列中,像这样进行: int foo[5][3]

那么我该如何读取这个文件呢?最后,该文件具有多组输入。因此,它可能会去:(2,2是第一组信息,以及3,4为第二组输入)

2 2 
9 2 
6 5 
3 4 
1 2 29 
9 6 18 
7 50 12 

如何从C++中的文件读取这种投入?

+0

我会制作一个矩阵类,它包含动态二维数组,并为该矩阵类重载'operator <<',以简单读入下一个n * m整数。 –

+0

你是否被迫使用数组或可以使用std :: vector? – Heisenbug

+0

@Heisenbug:看起来像codechef的措辞给我,但谷歌无法找到与这些确切的话拼图。 –

回答

2

首先,你应该有一个矩阵/格/ 2darray类某种

//A matrix class that holds objects of type T 
template<class T> 
struct matrix { 
    //a constructor telling the matrix how big it is 
    matrix(unsigned columns, unsigned rows) :c(columns), data(columns*rows) {} 
    //construct a matrix from a stream 
    matrix(std::ifstream& stream) { 
     unsigned r; 
     stream >> c >> r; 
     data.resize(c*r); 
     stream >> *this; 
     if (!stream) throw std::runtime_error("invalid format in stream"); 
    } 
    //get the number of rows or columns 
    unsigned columns() const {return c;} 
    unsigned rows() const {return data.size()/c;} 
    //an accessor to get the element at position (column,row) 
    T& operator()(unsigned col, unsigned row) 
    {assert(col<c && row*c+col<data.size()); return data[data+row*c+col];} 
protected: 
    unsigned c; //number of columns 
    std::vector<T> data; //This holds the actual data 
}; 

,然后你只需重载operator < <

template<class T> 
std::istream& operator>>(std::istream& stream, matrix<T>& obj) { 
    //for each row 
    for(int r=0; r<obj.rows(); ++r) { 
     //for each element in that row 
     for(int c=0; c<obj.cols(); ++c) 
      //read that element from the stream 
      stream >> obj(c, r); //here's the magic line! 
    } 
    //as always, return the stream 
    return stream; 
} 

相当简单。

int main() { 
    std::ifstream input("input.txt"); 
    int r, c; 
    while(input >> c >> r) { //if there's another line 
     matrix<char> other(c, r); //make a matrix 
     if (!(input >> other)) //if we fail to read in the matrix 
      break; //stop 
     //dostuff 
    } 
    //if we get here: invalid input or all done 
} 
+0

谢谢,真的很有用,但你可以评论一下吗?由于我在理解第一部分时遇到了一些困难。 – Annabelle

+0

@Link:完成。请记住,你的实际矩阵类可能应该有更多的方法,迭代器和其他类。我查看容器应该有的成员[here](http://stackoverflow.com/a/7759622/845092) –

+0

因此,在使用时,我是否打开文件并执行文件>>数组? – Annabelle

0

您需要一种方式来动态分配在运行时MEMOR,因为这是当你知道你需要多少数据从文件中读取。有(至少)两种方式来做到这一点:

  1. 使用std:矢量由@MooingDuck

  2. 的建议动态与newnew[]运营商分配您的阵列。您还需要确保使用deletedelete[]操作员释放任何内存。