好吧,我正在进行一些编程练习,并被一个涉及读取文件的练习所困扰。我需要做的是将一组特定的行读入二维数组,行的长度和行的数量各不相同,但我事先知道。
因此文件的格式如下:
There are two numbers,
n
andm
, where1 <= n, m <= 20
,
现在n
和m
进入格式如下的文件: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++ 文件中读取此类输入?
最佳答案
首先,您应该有某种矩阵/网格/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
};
然后你只需重载运算符<<
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
}
关于c++ - 使用 C++ 将某些行读入二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12484034/