c++arraysread-data

How to save a specific column into an array in C++?


I have a set of data in a .txt file that has an arbitrary number of columns, specified by the user in the input. I want to read that file, pick one of the columns and save it in an array. What is the best way to do this?

I have read this, this and this, but they all establish in the code the specific number of columns. I want it to be some input, so that the code is "general" and saves in that array the specific column from the input. Thank you!

EDIT: This is an example of how the input looks like - the total number of Columns (particles) is specified by the user. The output will be some other .txt of data coming from this one.

TIME     PART1       PART2       PART3       PART4  
0    0.0147496  934.902 0.0949583   -1192.37    0.0141576   950.604 0.0905118   -1074.44    
1.66667e-005    0.0147497   2804.7  0.0949583   -3577.12    0.0141576   2851.81 0.0905117   -3223.33    
3.33333e-005    0.0147497   4674.5  0.0949582   -5961.86    0.0141577   4753.02 0.0905116   -5372.21    
5e-005  0.0147498   6544.3  0.094958    -8346.6 0.0141578   6654.22 0.0905115   -7521.09    
6.66667e-005    0.01475 8414.09 0.0949578   -10731.3    0.0141579   8555.41 0.0905114   -9669.96

Solution

  • I assume the user enters the coumn number over the console. So you can use the built-in cin function to read the input. You can use for loop and string streams to get the values. Code below; although you may have tweek it a little bit as per your needs

    Edit: The code below has been edited a little bit. Now it should answer your question.

    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    int main()
    {
       int n;
       cin >>n; //user needs to input the column number
       fstream newfile;
       //newfile.open("file.txt",ios::out);  // open the file to perform write operation using file object; Activate this function if you want to overwrite
       newfile.open("file.txt",ios::in); //open the file to perform read operation using file object
       if (newfile.is_open())
       {
          string line;
          getline(newfile, line); //skipping the first line
          while(getline(newfile, line))//loop throuhg rest of the lines
          { 
                int temp=n;
                while(temp != 0)//loop until you get to the requied column
                {
                    getline(newfile, line, '\t'); //get the vaue separted by tab='\t'. Be sure that the last column also ends in '\t'
                    temp--;
                }
                cout<<line<<endl; //now line holds the element on the loop-row of the selected column
          }
          newfile.close(); //close the file object.
       }
    }