I have to read from a txt file these lines:
1 334.5909245845 161.7809319139
2 397.6446634067 262.8165330708
3 503.8741827107 172.8741151168
4 444.0479403502 384.6491809647
5 311.6137146746 2.0091699828
6 662.8551011379 549.2301263653
7 40.0979030612 187.2375430791
From here I have to extract the second and third values of each line because they're the coordinates for my cities. My piece of code is the following one (I will show only the part where the program has to read the values):
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdlib.h>
struct city {
double x;
double y;
};
int main(int argc, const char *argv[])
{
FILE *f;
f = fopen(argv[1], "r");
if (f == NULL)
{
printf("cannot read file or inexistant file.\n");
return 1;
}
char lines[2000][150];
int i = 0;
int j = 0;
int c = 0;
// read file's lines
while (c != EOF)
{
while ((c = getc(f)) != EOF && c != '\n')
{
lines[i][j] = c;
j++;
}
lines[i][j] = '\n';
i++;
j = 0;
}
strcpy(lines[i - 2], "\n");
struct city * cities = malloc(sizeof(double) * 10 + 1);
if (cities == NULL)
{
printf("cannot allocate memory");
return 1;
}
int counter = 0;
for (int y = 0; strcmp(lines[y], "\n") != 0; y++)
{
// don't need this check
if (isdigit(lines[y][0]))
{
char * tok;
struct city *new_city = malloc(sizeof(struct city));
if (new_city == NULL)
{
printf("cannot allocate memory");
free(cities);
return 1;
}
//read first number, not used
tok = strtok(lines[y], " ");
//read coordinate x
tok = strtok(NULL, " ");
printf("tok1: %s\n", tok);
new_city -> x = atof(tok);
//read coordinate y
tok = strtok(NULL, " ");
printf("tok2: %s\n", tok);
new_city -> y = atof(tok);
printf("inserted: %lf\n", new_city -> y);
cities[counter] = *new_city;
counter++;
}
}
fclose(f);
Simply I open the file, read char by char all lines, and then I use strtok() to take the coordinates written (second and third numbers of each line). The problem is that I have to store them into x and y of my city struct, and as I read here atof() must be used, but it approximate the number and then it return segmentation fault, as I printed here (inserted is city->y that is approximated but it is wrong, while tok1 and tok2 are the two correct strings read form the file):
tok1: 334.5909245845
tok2: 161.7809319139
inserted: 161.780932
tok1: 397.6446634067
tok2: 262.8165330708
inserted: 262.816533
tok1: 503.8741827107
tok2: 172.8741151168
inserted: 172.874115
tok1: 444.0479403502
tok2: 384.6491809647
zsh: segmentation fault ./Travelling_salesman_problem ch130.tsp
As you can see comparing the inserted value and tok2, inserted is approximated and then the code breaks. There is a way without changing the code but only the atof() function to have the precise value (because the rest of the code works)?