Created
October 26, 2019 01:54
-
-
Save airicbear/f331234f4abbd341891969849f47df88 to your computer and use it in GitHub Desktop.
Read files in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <math.h> | |
#define MAXNUM 100 | |
typedef struct Person | |
{ | |
double height; | |
double weight; | |
} Person; | |
int getData(char filename[], Person people[]) | |
{ | |
FILE *data; | |
int c = 0; | |
int i = 0; | |
double height, weight; | |
data = fopen(filename, "r"); | |
if (data == NULL) | |
{ | |
printf("Unable to open file\n"); | |
exit(1); | |
} | |
while(c < MAXNUM) | |
{ | |
int ret = fscanf(data, "%lf, %lf", &height, &weight); | |
if (ret == EOF) { | |
break; | |
} | |
people[c].height = height; | |
people[c].weight = weight; | |
c++; | |
} | |
fclose(data); | |
return c; | |
} | |
double getAverage(int data[], int length) { | |
int i, sum; | |
sum = 0; | |
for (i = 0; i < length; i++) { | |
sum += data[i]; | |
} | |
return sum / length; | |
} | |
int main(int argc, char **argv) | |
{ | |
char filename[] = "values.dat"; | |
Person people[MAXNUM]; | |
int numPeople, heightData[numPeople], weightData[numPeople]; | |
double aveHeight, aveWeight, stdHeight, stdWeight; | |
numPeople = getData(filename, people); | |
for (int i = 0; i < numPeople; i++) { | |
heightData[i] = people[i].height; | |
weightData[i] = people[i].weight; | |
} | |
printf("The average height is %lf\n", getAverage(heightData, numPeople)); | |
printf("The average weight is %lf\n", getAverage(weightData, numPeople)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment