读取二维表到数组
问题描述:
我有一个简单的程序,试图将二维数据读入堆分配的浮点数组中。该计划如下。读取二维表到数组
#include <iostream>
#include <fstream>
void read_file(std::ifstream &inFile, float **arr, unsigned m, unsigned n)
{
for(unsigned i = 0; i < m; ++i) {
for(unsigned j = 0; j < n; ++j) {
inFile >> arr[i][j];
std::cout << arr[i][j];
}
std::cout << std::endl;
}
}
int main() {
const unsigned m = 20;
const unsigned n = 1660;
float **A = new float *[m]; // alloc pointers to rows 1,...,m
for(unsigned row = 0; row < m; row++) A[row] = new float [n]; // alloc columns for each row pointer
std::ifstream inFile("data.dat");
read_file(inFile, A, m, n);
// DEALLOC MEMORY
for(unsigned row = 0; row < m; row++) delete [] A[row]; // dealloc columns for each row pointer
delete [] A; // dealloc row pointers
return EXIT_SUCCESS;
}
的数据是0-1条目表(见这里:data),其是很好的行取向,并且具有20行和1660列。我将打印添加到read_file
函数中以查看错误,并且仅打印零,但至少打印正确的数量(20 * 1660个零)。
数据似乎是制表符分隔的;是问题还是我的方法完全无效?
答
这正是如果文件不存在可能发生的事情。
您应该检查创建对象后,该文件存在,比如像这样:
std::ifstream inFile("data.dat");
if (!inFile)
{
std::cerr << "cannot open input" << std::endl;
return 1;
}
如果文件不存在,cin
不把数据数组中,并有机会(我有0 +其他奇怪的东西),所以总结它未定义的行为
请注意,如果该文件存在,您的程序将按预期工作。它甚至会更好,检查文件后看了一个值,以确保该文件还有许多价值预期:
for(unsigned j = 0; j < n; ++j) {
inFile >> arr[i][j];
if (!inFile)
{
std::cerr << "file truncated " << i << " " << j << std::endl;
return;
}
std::cout << arr[i][j];
}
+0
谢谢Jean。你是正确的,我需要指定工作目录到我的IDE,现在它工作! – ELEC
有趣的选择如何'VECTOR',你不使用它! –
我从'vector'开始,但后来我试着去了解'new'关键字。 – ELEC
这是一个不错的[C++书籍]列表(http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list)。我建议你看看它。对于* 2D阵列*使用矢量向量。 – 2016-12-30 10:05:17