Problem with reading from a .txt

Hi everybody!

I have a text file with both numbers and text.

ex.

12 2 3 h j \n
1 6 7 j k \n
5 8 k m \n

I want to store the first column in one array and the second column in another.

So the result should be something like this

c1[0] = 12, c1[1] = 1 and c1[2] = 5
c2[0] = 2, c2[1] = 6 and c[2] = 8

I'm not interested in the characters.

thanks in advance!
1
2
3
4
5
int c1[20], c2[20], c3[20];
char x1[20], x2[20];

for (int i = 0; i < 20 && infile.good; i ++)
   infile >> c1[i] >> c2[i] >> c3[i] >> x1[i] >> x2[i];


The above code assumes no more than 20 rows exist in the file and that the file is formatted as num num num char char.

I hope that helps.

I would use cin >> n to get the required integers. After the two ints, you want to ignore the rest of that line, so use either ignore() or getline() to read up to the end of the line.

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
35
36
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

    using namespace std;

    string data("12 2 3 h j \n1 6 7 j k \n5 8 k m \n" );

int main()
{
    vector <int> c1;
    vector <int> c2;

    istringstream infile(data);

    int n;
    while (infile >> n)
    {
        c1.push_back(n);
        infile >> n;
        c2.push_back(n);
        infile.ignore(100, '\n');
    }

    for (int i=0; i<c1.size(); i++)
        cout << c1[i] << " ";
    cout << endl;

    for (int i=0; i<c2.size(); i++)
        cout << c2[i] << " ";
    cout << endl;

    return 0;
}

Output:
12 1 5
2 6 8


Note, I used stringstream for convenience. This should work with a normal text file too.
Last edited on
Topic archived. No new replies allowed.