Gary Gary - 1 year ago 86
C Question

C programming: Finding max in a file string

I have this assignment that I can't figure out.

We have a file in the following format:

100 500 250 300
300 150 175
920 680
20 10 15 25 50 30 19 23

On the first line we have the total number of auctions.

Afterwards, each two rows represent an auction.

On the first row there is the number of bids. On the following row there are the actual bids.

For example the number 4 describes an auction with 4 bids (100,500,250,300).

My task is to determine the highest bid for each auction. This is what I've got so far. Any help will be appreciated.

#include <stdio.h>

int main() {

FILE * ifp;
char filename[100];

printf("File name\n");
scanf("%s", &filename);

ifp = fopen (filename, "r");

if (ifp == NULL) {
printf("Error, File could not be opened.\n");
return 1;
int i, num_auctions, auction, j, bid, max;

fscanf(ifp, "%d", &num_auctions);

for(i=0; i<num_auctions; i++) {
fscanf(ifp, "%d", &auction);
if (bid > max)
max = bid;
for(j=0; j<auction; j++){
fscanf(ifp, "%d", &bid);
printf("%d\n", bid);

printf("%d\n", max);

return 0;

Answer Source

These are the problems in your code.

  1. bid and max are used unintialised. Fix is to set them to 0 when they are declared.
  2. The if (bid > max) check is in the wrong spot. It's only checking the last bid of each auction. The fix is to move that check into the inner for loop after the fscanf.
  3. max needs to be cleared after each auction. The fix is to set max to 0 at the top of the outer for loop.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download