reading from different columns

I'm trying to read a .txt file with multiple columns, which all have the same number of spacing separated by a space but are different lengths. ie

123 456 25555555 45555555 8785488
123 456 49615 15664 4857452
etc.....

I want to pull in column 2 (essentially after the first space) into an array. Nothing before or nothing after. BTW i'm not putting the full code, just trying to figure out how I would write the array.

1
2
3
double array;

outFile << col2[2];



Read each line.
You can use the good old strtok function http://www.cplusplus.com/reference/cstring/strtok/ and split the line on space character.
This creates an array for each line.
Get the element of your choice from the array.
I take it to mean you want only the value "456" from the first line.
Then the value "456" from the second line etc.

The values look like integers, rather than floating-point (your code sample has "double").

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

int main()
{
    ifstream fin("data.txt");

    if (!fin)
    {
        cout << "could not open file" << endl;
        return 1;
    }

    int one, two;
    vector <int> array;

    // read first two columns, ignore the rest of the line
    while (fin >> one >> two)
    {
        array.push_back(two);
        fin.ignore(1000, '\n');
    }

    // display the contents of the vector
    for (int i=0; i<array.size(); i++)
    {
        cout << array[i] << endl;
    }

    return 0;
}

Topic archived. No new replies allowed.