我正在尝试从如下所示的文本文件中加载数据:
161,77,88,255 0,44,33,11,111
等我有操作它的功能,并确保数组的大小正确(可能仍然会有所不同)。以下是我的尝试:
bool loadData(int **imgPix, string fileName) {
ifstream inputFile;
inputFile.open(fileName.c_str());
string tempLineRow; //The resulting line from the text file
string tempElementColumn; //The individual integer element
int numberOfCols = 0;
int numberOfRows = 0;
if (!inputFile.is_open()) {
return false;
}
imgPix = new int* [numberOfRows];
while (getline(inputFile, tempLineRow, '\n')) {
stringstream ss;
ss << tempLineRow; //Stringstream version of the line
while (getline(ss, tempElementColumn, ',' )) {
stringstream ss2;
ss2 << tempElementColumn;
ss2 >> numberOfCols;
//Prob? (**imgPix) = *(*(imgPix + numberOfRows) + numberOfCols);
numberOfCols++;
}
numberOfRows++;
}
inputFile.close();
return true;
我已经用注释标记了带有双指针赋值的行,因为我相信它是我错误的根源,尽管可能还有其他错误。我不确定如何使用我实现的 while 循环结构来迭代更新二维数组。
任何人都可以提供任何帮助吗?将不胜感激!
最佳答案
imgPix = new int* [numberOfRows]
这里 numberOfRows = 0,所以你没有分配足够的内存。在分配内存之前,您需要知道数组的维度。 然后你还应该为数组中的每一行分配一个内存:
imgPix[currentRow] = new int [TotalCols];
对于二维矩形数组,创建 TotalRows*TotalCols 元素的一维数组,然后使用公式 A(row, col) = A[row*TotalCols + col]
.
关于c++ - 将数据从逗号分隔的文本文件加载到二维数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16623971/