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

Click For Summary
SUMMARY

The discussion focuses on transferring data from a text file into a dynamically sized 2D vector array in C++. The user encountered compilation errors due to incorrect type usage when attempting to push an istringstream into a vector>. The solution involves ensuring that the correct data type is pushed into the vector, specifically using vector to store the words read from the file.

PREREQUISITES
  • Understanding of C++ syntax and data structures
  • Familiarity with file I/O operations in C++
  • Knowledge of string manipulation using istringstream
  • Experience with dynamic memory allocation in C++
NEXT STEPS
  • Learn how to dynamically resize vectors in C++
  • Explore error handling techniques for file operations in C++
  • Study the use of istringstream for parsing strings
  • Investigate best practices for managing 2D arrays in C++
USEFUL FOR

C++ developers, students working on data structure assignments, and anyone looking to improve their skills in file handling and dynamic data storage in C++.

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!
 

Similar threads

  • · Replies 14 ·
Replies
14
Views
4K
  • · Replies 16 ·
Replies
16
Views
2K
  • · Replies 15 ·
Replies
15
Views
3K
  • · Replies 2 ·
Replies
2
Views
5K
  • · Replies 3 ·
Replies
3
Views
3K
  • · Replies 1 ·
Replies
1
Views
2K
  • · Replies 4 ·
Replies
4
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 6 ·
Replies
6
Views
3K
Replies
6
Views
2K