0

I have read columns from a .txt file (the file has at the beginning the number of columns (nCol)) and put the values into an array (float values[nCol][nLin]).

Now, I want to copy the values (ex.: values[0][nLin], values[1][nLin]...) into different float arrays depending on the number of columns.

How can I crate float arrays for each column if the number of columns my change depending on the file I am reading?

//------ Declares Array for values ------//
const int nCol = countCols;
float values[nCol][nLin];

// Fill Array with '-1'
for(int c=0; c<nCol; c++){
    for(int l=0; l<nLin; l++) {
        values[c][l] = -1;
    }
}


//------ Skips the reading of line of values file ------//
getline(inFile, dummyLine);

// reads file to end of *file*, not line 
while(!inFile.eof()) {
    for(int y=0; y<nLin; y++){
        for (int i=0; i<nCol; i++) {
            inFile >> values[i][y];
        }
    i=0;    
    }
}

const int nValues = countLines;

float Col1[nValues]=-1,
      Col2[nValues]=-1,
      Col3[nValues]=-1,
      Col4[nValues]=-1,
      Col5[nValues]=-1;

//------ Put values in specific Arrays ------//

for(int v=0; v<nValues; v++) {
        Col1[v] = values[0][v];
        Col2[v] = values[1][v];
        Col3[v] = values[2][v];
        Col4[v] = values[3][v];
        Col5[v] = values[4][v];
}
cout << endl;

I want that float Col1[] to be from 1 to nCol, the last one to be float ColnCol[]

2 Answers 2

3

The best way IMO would be to use std::vector< std::vector<float> >

You do not need to make different 1D columns as you can manipulate this vector of vector as you want.

Sign up to request clarification or add additional context in comments.

5 Comments

But is it possible with arrays? I have made the rest of the program and calculations with arrays
I don't think your program will need to change much since vectors work almost same as arrays (ofcourse with a lot more functionality). And to answer your question, if the number of lines is dynamic, then fixed length arrays cannot be used.
Sorry to ask, but can you give an example of how could I do it with vectors?
Instead of Col1[k], use values[0][k] everywhere.
I'm going to try it. Thank you
0

Instead you should use std::vector. It is a better choice for dynamic size allocation of a data type.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.