I'm working on a program here and I am accessing file input and am looping through an array of values in the file. However, it's not properly calculating the maximum value. Any help?
#include <stdio.h>
int main() {
int header, i, j, cur_val, auction[50], sum = 0;
int max = 0;
FILE * ifp;
ifp = fopen("input.txt", "r");
fscanf(ifp, "%d", &header);
for (i = 0; i < header; i++) {
fscanf(ifp, "%d", &cur_val);
printf("%d\n", cur_val);
for (j = 0; j < cur_val; j++) {
fscanf(ifp, "%d", &auction[j]);
printf("%d\n", auction[j]);
max = auction[0];
if (auction[j] > max) {
max = auction[j];
}
}//end j loop
printf("Max: %d\n", max);
printf("\n");
//printf("Auction %d was sold for $%.2f!\n", i+1, );
//sum+=max;
}//end i loop
fclose(ifp);
return 0;
}
Here's the file input:
5
4
100 500 250 300
1
700
3
300 150 175
2
920 680
8
20 10 15 25 50 30 19 23
The max values printed to the console are as follows:
300 700 300 920 23
The middle 3 work but not the first and last. Any idea why?
max = auction[0];out of the loop.fscanfto insure you are processing an actual value, not just garbage, (e.g.if (fscanf(ifp, "%d", &header) != 1) { /* handle error */ }) If you have a matching failure or conversion failure and fail to handle the error, you are in uncharted water from then on.:)