extract from stringstream into 2D vector

239 views Asked by At

This might be a stupid question, but anyway: I would like to obtain the numbers from a .txt file, which contains an adjacency matrice of a graph, the first row of the file contains only the number of nodes.

10

-1 5 3 -1 -1 -1 -1 -1 -1 -1

5 -1 -1 4 -1 -1 -1 -1 -1 -1

3 -1 -1 -1 -1 9 7 6 -1 -1

-1 4 -1 -1 2 -1 -1 -1 -1 -1

-1 -1 -1 2 -1 -1 -1 -1 -1 -1

-1 -1 9 -1 -1 -1 -1 -1 -1 -1

-1 -1 7 -1 -1 -1 -1 -1 4 2

-1 -1 6 -1 -1 -1 -1 -1 -1 -1

-1 -1 -1 -1 -1 -1 4 -1 -1 -1

-1 -1 -1 -1 -1 -1 2 -1 -1 -1

why doesn't it work in the right way? the output is the following:

10

10 0 0 0 0 0 0 0 0 0

5 0 0 0 0 0 0 0 0 0

3 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

-1 0 0 0 0 0 0 0 0 0

void beolvas (vector<vector<double> > & mygraph, string filename)
{
    ifstream input(filename);
    stringstream ss;
    char node[30];
char graph_size[2];

while(input.good()){

input.getline(graph_size,'\n');
cout << graph_size << endl;
ss << graph_size;
int graph_sizeINT = atoi(graph_size);
mygraph.resize(graph_sizeINT, vector<double>(graph_sizeINT,-1));
ss.clear();

for(int i=0; i<graph_sizeINT; i++)
    {

          input.getline(node,35,'\n');
          //cout << node << endl;
          ss << node;
         for(int j= 0; j<graph_sizeINT; j++)
          {
            ss.getline(node,' ');
            //cout << node << " ";
            mygraph[i][j] = atof(node);
            cout << mygraph[i][j] << " ";
          }
          cout << endl;
          ss << "";
          ss.clear();
   }
} input.close();   }

Thanks for any advice!

1

There are 1 answers

0
Beta On BEST ANSWER

You are using getline and stringstream, which are good tools, but not the right tools for this job; they are too powerful and require too much care. Rather than analyze exactly how they are going wrong, look at what happens when we dispense with them, in favor of stream input:

void beolvas (vector<vector<double> > & mygraph, string filename)
{
  ifstream input(filename.c_str());

  int graph_sizeINT;
  while(input >> graph_sizeINT)
    {
      cout << graph_sizeINT << endl;

      mygraph.resize(graph_sizeINT, vector<double>(graph_sizeINT,-1));

      for(int i=0; i<graph_sizeINT; i++)
        {
          char node[30];
          for(int j= 0; j<graph_sizeINT; j++)
            {
              input >> mygraph[i][j];
              cout << mygraph[i][j] << " ";
            }
          cout << endl;
        }
    }
  input.close();
}