Hi Guys,
I am a complete newbie to C++. I have a background in R, and have recently taken the plunge into C++. Not having much success though. I am trying to solve an easy problem (no doubt) - reading data from a tab delimited file and inserting it into a 2D array.
The data I have been trying to read is:
1 5 7 8 90
2 67 4 9 0
3 6 54 5 4
3 23 4 2 8
Here is my code:
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
using namespace std;
int main() {
string s, line, segments;
vector<string> v, v2;
ifstream in("test.txt");
stringstream ss;
string data [4][5];
// read in each line
while(getline(in,line)) {
v.push_back(line);
}
cout << v[0] << endl; // Printing out these
cout << v[1] << endl; // gives the expected
cout << v[2] << endl; // results.
cout << v[3] << endl;
// Try and sort elements of each line
// into a 2D array:
for (int i=0; i < 4; i++) {
ss << v[i]; // Suspected problem here
while (getline(ss,segments,'\t')) {
v2.push_back(segments);
}
for (int j=0; j < 5; j++) {
data[i][j] = v2[j];
cout << data[i][j] << endl;
}
}
}
Compiling and executing this code only prints out the elements of the first row of the input data. I suspect that "ss << v" is always pointing to the first element of the array. I am not sure how to remedy this though. If someone could give me a hand, or suggest a better method for solving this problem, I would be very grateful.
Ben.