Insert elements into vector of C ++ lists

2

I'm not able to insert elements into a list vector. The program prints the variable amount_of_vertices and then a run-time error occurs.

#include <iostream>
#include <list>
#include <vector>
#include <stdio.h>
using namespace std;

int main(int argc, char *argv[]){
    FILE *arq = fopen(argv[1], "r") ;
    int quantidade_de_vertices, vertice1, vertice2, cont;

    fscanf(arq, "%*c %*s %d %*d", &quantidade_de_vertices);
    cout << quantidade_de_vertices;

    vector< list<int> > adj(quantidade_de_vertices);

    while(!feof(arq)){
        fscanf(arq, "%*c %d %d", &vertice1, &vertice2);
        adj[vertice1].push_back(vertice2); //essa é a linha com o erro
    }
    fclose(arq);
    return 0;
}

The problem is this in the operator [] of the vector function that is not accepting the variable vertice1, because when I tried changing the line:

  

adj [vertice1] .push_back (vertice2);

by

  

adj [1] .push_back (vertice2);

and the program ran normally. The files are formatted as follows:

  

p edge 4 6

     

e 1 2

     

e 1 3

     

e 1 4

     

e 2 3

     

e 2 4

     

e 3 4

     

EOF

    
asked by anonymous 23.07.2017 / 20:47

1 answer

0

The problem is in fscanf and in reading line term, \n .

In the first line it works fine, and it reads the 4 values but in the second line, through debug you quickly see that the reading did not work well:

Wherevertice2stayedwith4201420andvertice1with2686760.

Thisisbecausethe\nofthefirstlinewasnotconsumedandspoiledthesuccessivereadings.Sothesolutionissimple,justchangethefirstfscanfto:

fscanf(arq,"%*c %*s %d %*d\n", &quantidade_de_vertices); //agora com \n no fim

And what's inside while also:

fscanf(arq, "%*c %d %d\n", &vertice1, &vertice2); //também com \n
    
23.07.2017 / 22:14