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

AI Thread Summary
The discussion focuses on transferring data from a text file into a dynamically sized 2D vector array in C++. The user is attempting to read a file containing numerical data and push each number into a vector of vectors. A compilation error arises because they are trying to push an `istringstream` object into a `vector<vector<string>>`, which is a type mismatch. The user also realizes that their vector declaration is incorrect, as it mistakenly uses parentheses, leading to an empty function declaration instead of a vector. The conversation emphasizes the importance of matching data types and correcting the vector initialization.
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) {cout<<"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!
 

Similar threads

Replies
15
Views
3K
Replies
2
Views
4K
Replies
3
Views
2K
Replies
1
Views
2K
Replies
1
Views
2K
Replies
6
Views
3K
Back
Top