1. Not finding help here? Sign up for a free 30min tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Apr 16, 2012 #1
    1. The problem statement, all variables and given/known data

    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.

    2. Relevant equations



    3. 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;
    }
     
  2. jcsd
  3. Apr 16, 2012 #2

    I like Serena

    User Avatar
    Homework Helper

    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 (Text):
    vector<vector<string>>a();
     
    Last edited: Apr 16, 2012
  4. Apr 17, 2012 #3
    Oh yes, I got it. Thank you!
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Transfering data from a text file into a 2D vector array in c++
Loading...