Populating an array from a .txt file

242 Views Asked by At

I'm trying to populate an array from a .txt that I am reading. I am using this code that I am using as a function to read the file:

double* read_text(const char *fileName, int sizeR, int sizeC)
{
    double* data = new double[sizeR*sizeC];
    int i = 0;
    ifstream myfile(fileName);
    if (myfile.is_open())
    {

        while (myfile.good())
        {
            if (i > sizeR*sizeC - 1) break;
            myfile >> *(data + i);
            //cout << *(data + i) << ' '; // Displays converted data.
            i++;
        }
        myfile.close();
    }

    else cout << "Unable to open file";
    //cout << i;

    return data;
}

Now when I read the file I am trying to take the elements from the 1D data array and store them into a 2D array.

I've tried to create an array in a public class, however I have no idea on how to move the data that I am reading to a 2D array.

I know it's not very clear but basically I'm doing the nearest neighbour search algorithm to compare 2 images. I have taken one image and converted it into the values using this bit of code above. However now I am trying to store the data that I am reading into a 2D public array?

2

There are 2 best solutions below

0
On

Here is a more compact version of reading in a 2D matrix:

int quantity = sizeR * sizeC;
double * matrix = new double [quantity];
double value = 0.0;
double * p_cell = matrix;
//...
while ((myfile >> value) && (quantity > 0))
{
  *p_cell++ = value;
  --quantity;
}

In the above code snippet, a pointer is used to point to the next slot or cell of the matrix (2D array). The pointer is incremented after each read.

The quantity is decremented as a safety check to prevent buffer overrun.

0
On

Assuming every double returned represents a pixel. You can define a function that retrieves pixels like so:

double get_pixel(int x, int y, double* data, int sizeC)
{
    return data[x + y*sizeC];
}

Where sizeC is the width of the image (number of columns).

You can then use the function above to fill your 2D array like so:

for(int i = 0; i < sizeC; i++)
    for(int j = 0; j < sizeR; j++)
        my2Darray[i][j] = get_pixel(i, j, data, sizeC);

But then notice how unnecessary this is. You don't really need a 2D array :) keep it simple and efficient.

The function above could be a part of a struct that represents the Image where you'd have sizeC, sizeR and data defined as members.

struct Image
{
    int sizeC;
    int sizeR;
    double* data;

    get_pixel(int x, int y)
    {
        return data[x + y*sizeC];
    }
};

Then to access the image pixels you can simply do:

Image img;
// read image data and stuff
double p = img.get_pixel(4, 2);

You can even make it look prettier by overriding the operator() instead of get_pixel so retrieving the pixel would look something like:

double p = img(4, 2);