Transfering data from a text file into a 2D vector array in c++

Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
2 replies · 6K views
Absolutism
Messages
27
Reaction score
0

Homework Statement



I am attempting to transfer the data from a file into a 2D vector array. The data look like this:
1 2 3
4 5 6
7 8 9

However, the dimensions must be detected dynamically.

Homework Equations


The Attempt at a Solution


There are two files in this code, but I attempted to transfer only one of them. I tried to read line by line and then take each word and push it into the array of vectors. The program does not compile though.

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>

using namespace std;

int main ( ) {
ifstream infile1;
ifstream infile2;
infile1.open ("Array.txt");
infile2.open ("Pattern.txt");
if (!infile1||!infile2) {count<<"error"; return -1;}

string line; string word;
vector<vector<string>>a();while (!infile1.eof())
{
getline (infile1, line);
istringstream stringline (line);
while ( stringline >> word ) {
istringstream strw (word);
a.push_back(strw); //the error is here. The "a." specifically.
}
return 0;
}
 
Physics news on Phys.org
Hi Absolutism! :smile:

You're trying to push_back() an istringstream onto a vector of vector<string>.
That's not possible.
The type does not match...

Btw, don't you get a compilation error on the following line?
Code:
vector<vector<string>>a();
 
Last edited:
Oh yes, I got it. Thank you!