Dec 8, 2012 at 4:46pm UTC
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!
Dec 8, 2012 at 6:24pm UTC
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:
Note, I used stringstream for convenience. This should work with a normal text file too.
Last edited on Dec 8, 2012 at 6:44pm UTC