Search code examples
carraysfor-loopbubble-sort

Program to bubble sort a txt file in C


I'm writing a C program to be given a txt file containing names of player and how many wins they have (its for a bigger game project), and sort them from highest to lowest amount of wins. While the code compiles and successfully orders the wins im experiencing a problem with the names where they seem to be stacking on top each other.


#include<stdio.h>
 #include<stdlib.h>

    char name[20];
    int wins[20];


void main()
{

    FILE *fp;
    int i=0,size,j,swap;
    char ch; 

    fp=fopen("record.txt","r");
    if(fp==NULL)
    { 
    printf("\n Cannot open the file \n");
    exit(0);
    }
    while(ch!=EOF)
    {
    fscanf(fp,"%s %d",&name[i],&wins[i]);  
    ch=fgetc(fp); 
    i++;  
    } 
    size=i-1;
    for(i=1;i<size;++i)
    for(j=0;j<size-i;j++)
    if(wins[j+1]>wins[j])

    {

        swap    = wins[j];
        wins[j]   = wins[j+1];
        wins[j+1] = swap;

        swap      = name[j];
        name[j]   = name[j+1];
        name[j+1] = swap;
    }
    fp=fopen("sortedRecord.txt","w");
    for(i=0;i<size;i++){
    fprintf(fp,"%s %d \n",&name[i],wins[i]);
    printf ("%s %d \n", &name[i],wins[i]); 
    }


    fclose(fp); 

}

Here is the input file "record.txt"

Andrew 5
Billboy 10
Hill 7
Mill 1

And here is what i get when i run it.

BHAMill 10 
HAMill 7 
AMill 5 
Mill 1 

I'm new to code so i know mine sucks but for the life of me i cant see exactly where its going wrong. Any help or advice is appreciated.


Solution

  • As jwdonahue said the issue is with your definition of name. char name[20] creates an array of 20 chars, not 20 strings.

    When you run the while(ch!=EOF) loop what's happening? First time through you find the address of the 0th element in name and write Andrew there so name has ['A', 'n', 'd', 'r', 'e', 'w', '\0', '\0', '\0', '\0'] (the \0 is the end of string character). Second time through you find the address of the 1st element in name and write Billboy, but the 0th element is still there and hasn't changed so you end up with the contents being ['A', 'B', 'i', 'l', 'l', 'b', 'o', 'y', '\0', '\0']. Adding Hill to the 2nd position results in ['A', 'B', 'H', 'i', 'l', 'l', '\0', 'y', '\0', '\0']. Then finally adding Mill gives the array ['A', 'B', 'H', 'M', 'i', 'l', 'l', '\0', '\0', '\0'].

    When you then go to sort scores you are sorting the characters in this array which end up as ['B', 'H', 'A', 'M', 'i', 'l', 'l', '\0', '\0', '\0'] (only the first four characters will be affected by your sort). In your print statement you then print the character array starting at the 0th, 1st, 2nd and 3rd positions respectively so you get BHAMill, HAMill, AMill, and Mill.

    Hopefully that should help you enough to get you unstuck. :)