c++ - 将数据从逗号分隔的文本文件加载到二维数组?

标签 c++ arrays pointers 2d double

我正在尝试从如下所示的文本文件中加载数据:

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/

相关文章:

c++ - 如何在 kdevelop 中修改项目的 CMakeList 文件

c++ - Qt复选框选中所有按钮

java - 将 .txt 文件中的数字读入二维数组并在控制台上打印

Java-数组 : How do i find the number that has a similar digit most times?

c - 垂直冗余检查中的段错误

c - sizeof 运算符在 C 中接受哪些参数?

c - 结构指针类型转换错误分配使指针来自整数而不进行转换

c++ - IME - 如何处理按键

c++ - 导出两个命名空间中的重复函数 (C++)

arrays - postgresql:任何子查询返回数组