I'm trying to read in a graph with space separated edges. Having an issue parsing from the char* buffer to the ints.
sample graph:
1 2
1 3
2 3
3 4
4 5
1 5
5 6
1 6
output:
first edge: 1
second edge: 2
first edge: 0
second edge: 0
first edge: 1
second edge: 3
first edge: 0
second edge: 0
first edge: 2
second edge: 3
first edge: 0
second edge: 0
first edge: 3
second edge: 4
first edge: 0
second edge: 0
first edge: 4
second edge: 5
first edge: 0
second edge: 0
first edge: 1
second edge: 5
first edge: 0
second edge: 0
first edge: 5
second edge: 6
first edge: 0
second edge: 0
first edge: 0
second edge: 0
first edge: 1
second edge: 6
first edge: 0
second edge: 0
first edge: 0
second edge: 0
obviously all those zeroes shouldn't be there.
code:
#include <stdio.h>
#include <math.h>
#include <ctype.h>
int main(int argc, char* argv[]){
FILE *fin;
fin = fopen(argv[1], "r");
int n_e = 0;
char* buffer = (char*)malloc(2048);
char* n1 = (char*)malloc(256);
char* n2 = (char*)malloc(256);
int v_1 = 0;
int v_2 = 0;
int flag = 0;
while(!feof(fin)){
int bytes_read = fread(buffer, 1, 2048, fin);
for(int i = 0; i < bytes_read; i++){
if(isdigit(buffer[i])){
if(flag == 0){
n1[v_1++] = buffer[i];
}
else
n2[v_2++] = buffer[i];
}
else if(buffer[i] == ' ')
flag = 1;
else{ //end of the line??
n_e++;
flag = 0;
n1[v_1++] = '\0';
n2[v_2++] = '\0';
int first = atoi(n1);
int second = atoi(n2);
printf("first edge: %d\n", first);
printf("second edge: %d\n", second);
v_1 = 0;
v_2 = 0;
}
}
}
return 0;
}