-2

So, I need to store the data from the text file into 2d array. I tried using vectors. So here is the sample data from the text file:

START  13
PID   11 
CORE 120
SSD 0
CORE 60
SSD 0
CORE 20
SSD 0

I want to store this data as final_vec[x][y]. This is what I tried:

void read_file(const string &fname) {
    ifstream in_file(fname);
    string line;
    vector<string> temp_vec;
    vector<vector<string>> final_vec;

    while ( getline (in_file,line) )
    {
        stringstream ss(line);
        string value;
        while(ss >> value)
        {
            temp_vec.push_back(value);
        }
        final_vec.push_back(temp_vec);
    }

    for (int i = 0; i < final_vec.size(); i++) { 
        for (int j = 0; j < final_vec[i].size(); j++) 
            cout << final_vec[i][j] << " "; 
                cout << endl; 
    } 

}

int main()
{
    read_file("test.txt");
    return 0;
}

I get error:

main.cpp: In function ‘void read_file(const string&)’:
main.cpp:29:29: error: variable ‘std::stringstream ss’ has initializer but incomplete type
         stringstream ss(line);

I am not sure if I am on the right track.

E_net4
  • 27,810
  • 13
  • 101
  • 139
Bayram
  • 73
  • 11
  • 1
    Have you included sstream? – EDD Feb 07 '20 at 01:12
  • 2
    Does this answer your question? [C++ compile error: has initializer but incomplete type](https://stackoverflow.com/questions/13428164/c-compile-error-has-initializer-but-incomplete-type) – infinitezero Feb 07 '20 at 01:23

1 Answers1

0

IMHO, a better solution is to model each line as a record, with a struct or class:

struct Record
{
  std::string label;
  int         number;

  friend std::istream& operator>>(std::istream& input, Record& r);
};

std::istream& operator>>(std::istream& input, Record& r)
{
    input >> r.label;
    input >> r.number;
    return input;
}

The overloaded operator>> makes the input loop a lot simpler:

std::vector<Record> database;
Record r;
while (infile >> r)
{
    database.push_back(r);
}

Rather than have a 2d vector of two different types, the above code uses a 1D vector of structures.

Thomas Matthews
  • 56,849
  • 17
  • 98
  • 154