1
  a   b
00001 3
00002 2
00003 1 4
00004 2 4 5
00005 1 2
00006 1 2 4
00007 2 5
00008 3 4 5
00009 3 4 5
00010 2 3

This is my data, I open it in C++ with getline and I wish to split them into a 2D vector. wish to have a 10*2 array which first column is a and second column is b. What should I do?

This is my code

int row = 0;
int column = 2;
string line;
vector<vector<string>>info;
ifstream data("C:\\01_test.txt");
while (getline(data, line))
{

    row++;
}
data.close();
0

2 Answers 2

1

You can do sth like that:

string line;
int main(){
 vector<vector<string> > info;
 ifstream data("C:\\01_test.txt");
 static int cnt=0;
 while(getline(data, line)){
  istringstream iss(line);
  info.push_back(vector<string>());
  copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(info[cnt]));
  cnt++;
 }
};

if you wanna use vector of int use some function to change string to int like atoi.

Sign up to request clarification or add additional context in comments.

8 Comments

00001 3 00002 2 00003 1 00004 2 00005 1 00006 1 00007 2 00008 3 00009 3 00010 2 this is the output but the it lost some of data
Can You show me complete snipet of Youre code? My output: 00001, 3, 00002, 2, 00003, 1, 4, 00004, 2, 4, 5, 00005, 1, 2, 00006, 1, 2, 4, 00007, 2, 5, 00008, 3, 4, 5, 00009, 3, 4, 5, 00010, 2, 3,
string line; vector<vector<string>>info; ifstream data("C:\\01_test.txt"); static int cnt = 0; while (getline(data, line)) { istringstream iss(line); info.push_back(vector<string>()); copy(istream_iterator<string>(iss), istream_iterator<string>(), back_inserter(info[cnt])); cnt++; } for (int i = 0; i < 10; i++) { for (int j = 0; j < 2; j++) cout << info[i][j]<<" "; cout << endl; } data.close();
You are printing only 2 elems each time for (int j = 0; j < 2; j++) cout << info[i][j]<<" "; Try printing by: for(int i=0; i<info.size(); ++i) { copy(info[i].begin(), info[i].end(), ostream_iterator<string>(cout, ", ")); }
I think you misunderstood my question. actually I am wanting a 10*2 array where first column is 00001 and second column is 3
|
0

The easiest way is to use the istringstream. If you look at the example in the link, it should be quite obvious.

2 Comments

sorry, I am new in programming can you help write an example?
it just show me the left handside, how about the right handside?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.