So I am new to C programming but was tasked to create a program that reads data from a file and then prints it out.
One of the sub-tasks is to calculate distance between 2 points through the haversine formula.
Now here is where my question comes in. How can I use some local variables defined from one of my functions in another function? If I can work this out, I will be able to do most of the rest of my task so I am really hoping there is a way to do this. I have tried working this out for the last day and have gotten no where.
I have included the code here. I will highlight the variables I want to use between functions. If it isn't immediately obvious, I am hoping to keep token[1] and token[2].
Code:
int main() { int i = 0;
double readfile, stage2;
readfile = read_file(i);
stage2 = stage_2_distance(i);
printf("%f %f", readfile, stage2);
return 0;
}
double read_file(double i) {
/* This function takes the data from the input file,reading and printing the
User ID, Location (longitude and latitude), Date, Time, and Distance*/
char length[256];
char *token[6];
double r_lat, r_long;
if (fgets(length, 256, stdin) != NULL) {
token[0] = strtok(length, " ");
int i = 0;
double dist = 0;
for (i = 1; i < 6; i++)
token[i] = strtok(NULL, " "); /*C programming is fun*/
printf("Stage 1\n==========\n");
printf("User: #%s\n", token[0]);
printf("Location: <%s, %s>\n", token[1], token[2]); /* token [1] and token [2] are the variables I want to use elsewhere. */
printf("Date: %s\n", token[3]);
printf("Time: %s\n", token[4]);
printf("Distance to reference: %.2f\n", distance(dist));
r_lat = *token[1]; /* These next two lines are what I have been playing around with*/
r_long = *token[2];
}
else {
printf("Error opening file. Check file and try again.");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
double distance(double d) {
/* This function is designed to calculate the distance between the check-in
POI and the reference point provided*/
double angle_distance, chord_length;
double lat_2, long_2;
int i = 0;
char length[256];
char *token[6];
token[0] = strtok(length, " ");
token[i] = strtok(NULL, " ");
double dist;
lat_2 = atof(token[3]);
long_2 = atof(token[4]);
double var_lat = toRadian(lat_2 - LAT_1);
double var_long = toRadian(long_2 - LONG_1);
double nLAT_1 = toRadian(LAT_1);
double nLat_2 = toRadian(lat_2);
chord_length = pow(sin(var_lat/2),2) + (cos(nLAT_1) * cos(nLat_2) *
pow(sin(var_long/2),2));
angle_distance = 2 * atan2(sqrt(chord_length), sqrt(1 - chord_length));
dist = 6371 * angle_distance;
return dist;
}
double toRadian(double x) {
x = PI/DEGREES;
return x;
}