0

I wrote this program for my C class. It basically takes the user to a horse track, display odds on different horses and allows the user to make a bet. Originally, my instructor only wanted us to write the results to a text or binary file, so the past results could be viewed whenever the user wanted.

He recently told us that he wants us to include bubble sort to group the horses in order i.e. horse 1, horse 1, horse 1, horse 1, horse 2, horse 2...etc.

I am sure I can figure out the bubble sort using strcmp(), but he also wants us to display how many times that horse has won the race in the past.

My question is: will I be able to make such a display dealing only with char/string arrays? I don't want to spend my next four hours building a solution that cannot work.

Thanks in advance,

p.s. Here is the function for that part of the program.

void viewWinners() {
    FILE *zacksTrackStats;

    char horses[MAX_SIZE] = {0};        

    if ((zacksTrackStats = fopen("zacksTrackStats.txt", "r")) == NULL)
    {
        perror ("error");
        exit (0);
    }

    while (fgets(horses, sizeof(horses), zacksTrackStats) != NULL)
    {
        printf ("%s", horses);
    }

    fclose(zacksTrackStats);
    pause;
}
Lily Ballard
  • 182,031
  • 33
  • 381
  • 347
Michael Brooks
  • 489
  • 4
  • 15

3 Answers3

1

Of course you can. Are the actual names "horse 1" and "horse 2"? If so you can just store each horse's data in an integer array. If not then you have to make a lookup table. Store information for how many times each horse has won and print the result.

thecooltodd
  • 264
  • 1
  • 3
  • 11
  • Thanks, Does it matter how the data is written to a text file or can I manipulate the data however I want when I read from the file? – Michael Brooks Jan 30 '13 at 22:13
  • Just manipulate the data however you want when you read from the file. The user isn't supposed to know how you store your data. The important thing from the user side is that the information is displayed the way that they want to see it. – thecooltodd Jan 31 '13 at 03:02
1

It is entirely possible to translate txt to numbers and vice versa.

Check out this older post: Converting string to integer C

Community
  • 1
  • 1
Nicolas
  • 93
  • 6
1

Yes you can. To manipulate data from the file you can use fscanf (or sscanf).

sscanf(char *source, format, &dest, ...)

For example :

int occurences[NUMBER_OF_HORSES_MAX];
int count = 0;
int temp = 0;
int i;

for(i = 0; i < NUMBER_OF_HORSES_MAX; ++i)
{
    occurences[i] = 0;
}

while (fgets(horses, sizeof(horses), zacksTrackStats) != NULL)
{
    sscanf(horses, "%d", &temp);
    occurences[temp] += 1;

    printf ("Current horse : %s", horses);

    count++;
}

for(i = 0; i < count; ++i)
{
    printf("Horse %d has won %d times\n", i, occurences[i]);
}
rombdn
  • 101
  • 1
  • 7