Shi Yi Lee
Shi Yi Lee

Reputation: 37

storing a string into 2D array

  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();

Upvotes: 1

Views: 202

Answers (2)

Temple
Temple

Reputation: 1631

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.

Upvotes: 1

David van rijn
David van rijn

Reputation: 2220

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

Upvotes: 0

Related Questions