Reputation: 1
I'm trying to make a program in which I can read a file with animals weight and calculate the weight average. I got this error while trying to compile. Does anyone knows why?
funciones.c
#include "header.h"
float count_animals(FILE *file){
float total_animals = 0;
char word[20];
while (fscanf(file, "%s", word) == 1){
total_animals++;
}
return total_animals;
}
float sum_weight_animals(FILE *file){
float sum_weight = 0;
float weight[20];
while (fscanf(file, "%f", weight) == 1){
sum_weight += weight;
}
return sum_weight;
}
header.h
#include <stdio.h>
#define MAXWORD 80
float count_animals(FILE *file);
float sum_weight_animals(FILE *file);
Just in case here's the main.c Now I have the problem that it's not adding up the sum_weight value in sum_weight_animals function.
#include "header.h"
int main(){
char WORD[MAXWORD];
char file_name[MAXWORD];
FILE *fileptr;
printf("Please, enter a file name: ");
scanf("%s", file_name);
printf("Reading file %s...\n", file_name);
fileptr = fopen(file_name, "r");
if(fileptr == NULL){
fprintf(stderr, "ERROR: The file '%s' doesn't exists\n", file_name);
return 1;
}
float total_animals = count_animals(fileptr);
if (total_animals > 0){
printf("There're %.2f animals.\n", total_animals);
}
else{
fprintf(stderr, "WARNING: File not found or it's empty\n");
}
float total_sum = sum_weight_animals(fileptr);
if (total_sum > 0){
printf("The sum of all animal's weight is %.2f [kg].\n", total_sum);
}
else{
fprintf(stderr,"WARNING: File not found or it's empty\n");
}
fclose(fileptr);
return 0;
}
When ex Makefile, it compiles correctly and the first function works fine, but the second one doesn't and it gives me the WARNING: File not found or it's empty\n that I put on main.c
Upvotes: 0
Views: 54
Reputation: 385764
Replace
float weight[20];
with
float weight;
and replace
fscanf(file, "%f", weight)
with
fscanf(file, "%f", &weight)
Explanation:
sum_weight += weight;
is basically equivalent to
sum_weight = sum_weight + weight;
Let's look at the right-hand side, sum_weight + weight
.
sum_weight
is a float
.weight
is an array of 20 float
elements.What does it mean to add a float and an array together? Nothing, that's what. This makes no sense.
You assigned a value to weight[0]
, and this is the value you want to add. Not weight
.
But why is weight
an array in the first place? As the name implies, it's only used to store one weight. You only ever assign to weight[0]
. So it makes no sense to use an array.
Upvotes: 3