As my project states, I need to make a program which reads a file and finds 2 of the largest and the smallest values in the file. This is my program, it seems to find the largest and the smallest, but does get the the second largest and smallest. The fscanf
for two small and two big does not seem to get a value from the file, and thus I get random values for the answer as well. I don't know whats wrong, if you can tell me whats wrong it would be great.
#include <stdio.h>
int
main (void)
{
FILE *in; /*names the file*/
int onesmall, twosmall, compare, onebig, twobig;
in = fopen("file2.data", "r"); /*opening the file*/
fscanf(in,"%d", &onesmall); /*scans and inputs first value (lowest value as of now)*/
fscanf(in,"%d", &onebig);
fscanf(in,"%d", &twobig);
fscanf(in,"%d", &twosmall);
while(!feof(in)){ /*loops till reaches to end of file*/
fscanf(in,"%d", &compare); /*scans and inputs first value*/
if (compare <= onesmall){
onesmall = compare; /*checks if value in compare is smaller than value in onesmall if it is then it will relace it*/
}
if (compare >= onebig){
onebig = compare; /*checks if value in compare is greater than value in onebig if it is then it will relace it*/
}
}
while(!feof(in)){
fscanf(in,"%d",&compare);
if (compare <= twosmall && compare != onesmall){ /*if value in compare is smaller than twosmall and not eaual to onsmall replace it*/
twosmall = compare;
}
if(compare >= twobig && compare != onebig){ /*if value in compare is greater than twobig and not eaual to onebig replace it*/
twobig = compare;
}
}
printf("The lowest value in the file is: %d\n", onesmall);
printf("The second lowest value in the file is: %d\n", twosmall);
printf("The greatest value in the file is: %d\n", onebig);
printf("The second greatest value in the file is: %d\n", twobig); /*prints output*/
fclose(in);
return (0);
}