Sachin S
Sachin S

Reputation: 33

Input using stdin in C/C++

I have to read graph inputs (all at once) (an example below):

6 8 //no of vertices, edges
0 1 2 //connectivity from vertex 0 to vertex 1, with weight 2
0 2 1
0 4 2
1 2 4
2 3 5
3 4 5
4 1 2
4 5 5

What is the best way to read inputs dynamically. I have to read all the above content at once. I need to read it dynamically since the number of edges and vertices can change, with a maximun of 10000. The following doesn't work:

int *twod_array; 
int N,M; //no of vertices, edges
scanf("%d %d", &N, &M);
twod_array = (int *)malloc(sizeof(int)*N*M); //where N = no of rows, M = no of cols
for(i=0; i < N; i++) {
  for(j=0; j < M; j++) {
scanf("%d",&twod_array[i*M +j]);
  }
}
for(i=0; i < N; i++) {
  for(j=0; j < M; j++) {
    if(twod_array[i*M +j] == "\0") {
twod_array[i*M +j] = 0;
    }
  }
}

Also, is this the best way for graphs in C/C++ or is it better to use struct, since traversals will be done.

Upvotes: 0

Views: 185

Answers (2)

debugman
debugman

Reputation: 125

From my experience, using an Edge struct will be very feasible to handle graph problems.

struct Edge{
    int to;
    int weight;
    Edge(int t, int w):to(t), weight(w){};
};
std::vector<vector<Edge> > graph;
int N,M; //no of vertices, edges
scanf("%d %d", &N,&M);
graph.resize(N);
int u, v, w;
for(int i = 0; i < M; i ++){
    scanf("%d %d %d", &u, &v, &w);
    graph[u].push_back(Edge(v, w));
}

Upvotes: 1

Jameson
Jameson

Reputation: 6679

As far as loading that data in goes, there are lots of ways. One would be to make a connectivity struct, and dynamically allocate an array of those based on the number of edges value in the first line of the data file:

#include <stdio.h>
#include <stdlib.h>

struct connectivity {
    int source;
    int sink;
    int weight;
};

int main() {
    int num_verts = 0;
    int num_edges = 0;
    struct connectivity *edges = NULL;
    int i = 0;

    scanf("%d %d\n", &num_verts, &num_edges);

    edges = malloc(sizeof (struct connectivity) * num_edges);

    for (i = 0; i < num_edges; i++) {
        scanf("%d %d %d\n", &(edges[i].source), 
                            &(edges[i].sink),
                            &(edges[i].weight));
    }

    // use edges here

    free(edges);
}

Also, please use more legible variable names!

Upvotes: 1

Related Questions