0

I've to make a program with c++ for my thesis that open and extract only two columns from a file .dat that is like this, with a lot of lines:

0.000000 -9.833374 1.000000 0.156921 0.125478 0.350911
5.015625 -9.831743 1.000000 0.157021 0.125752 0.349945
10.015625 -9.838824 1.000000 0.157101 0.125566 0.351512

I've obtained to open and read each lines with the command getline(), but i have no idea of how to extract only the columns that i need (in particular the second and the fourth). I am a very beginner using this programming language, so can somebody give me examples or indications of how to obtain this task?

Thank you very much

  • 1
    See [Split a string in C++?](http://stackoverflow.com/questions/236129/split-a-string-in-c) for examples of how you could extract the values from each line. – melak47 Nov 09 '15 at 09:57

1 Answers1

2

You can use stringstream for this:

ifstream file("data.dat")
string line;

while (getline(file,line))
{
    istringstream ss(line);

    // possibly you will want some other types here.
    string col2;  
    string col4;

    ss >> col2;    // extracts 1st col.
    ss >> col2;    // extracts 2nd col.

    ss >> col4;    // extracts 3rd col.
    ss >> col4;    // extracts 4th col.

    // Now you can something with col2 and col4
    cout << col2 << " " << col4 << endl;

}

Note that first I extract the first column to col2 and then overwrite it with the second column. I do it analogously for col4.

Of course you can use other types for col2 and col4, as long as this is consistent over your file.

Also if you do not want to read in columns, just to throw them away afterwards have a look at std::istream::ignore, which let's you skip over input.

oo_miguel
  • 2,374
  • 18
  • 30
  • So using this syntax (col1 and col2) my program understand automatically that i'm relating to the first and second column of the .dat file? – Paolo Orsatti Nov 09 '15 at 10:28
  • @PaoloOrsatti No! the identifiers make no difference. The `>>` operator will simply read in one column each time it is called. so calling `ss >> col;` two times will read in the first column to col and then the second column to the **same variable** (overwriting the first column stored before) – oo_miguel Nov 09 '15 at 10:36
  • Thank you very much! You solved my problem, now i can extract the column that i want. – Paolo Orsatti Nov 09 '15 at 15:02
  • Now i have another problem: i have to comparate a data of the n-line of a column, with the data of the (n+1)line of the same column. Solutions? – Paolo Orsatti Nov 09 '15 at 15:12
  • @PaoloOrsatti you're welcome. Having this problem solved you should create a **new** question for your **new problem** ;) – oo_miguel Nov 09 '15 at 15:32