The program is written in C language.
OS: Linux Ubuntu.
Editor: Sublime Text 3.
The getDataFromFile () function reads an array of structures and returns the number of records in the file. In the cycle, it searches for all the expenses and then, after the cycle, divides them into the average number of records (ie, it searches for the average monthly consumption). But when compiling, it outputs either 0.000000 or "Segmentation fault (core dumped)".
void average_spends() { int n = getDataFromFile(); float mspend = 0; for(int i; i < n; i++) { mspend += recover[i].all; } mspend = (float)mspend / (int)n; printf("%f\n", mspend); } The structure is declared as follows:
typedef struct Recover { char month[40]; int year; float food; float rent; float other; float all; } Recover; Function getDataFromFile ():
int getDataFromFile() { FILE *file; char *file_name = "text.txt"; file = fopen(file_name, "r"); int is = 0; while(!feof(file)) { fscanf(file, "%s %d %f %f %f %f", recover[is].month, &recover[is].year, &recover[is].food, &recover[is].rent, &recover[is].other, &recover[is].all); is++; } return is-1; } How to solve the above problem?
inot assigned to anything. Try initializing it to zero. - Ainar-G