JDCode
JDCode

Reputation: 1

Arranging a character array using bubble sort

Here is my code so far. I am perfectly able to sort files holding numbers but clueless when it comes to characters. It takes in a file of my choosing and outputs another file with the sorted array. But so far all I'm getting are blank files and I can't figure out why.

So how can I fix my code to sort an array of characters and then output it?

#include <stdio.h>

int bubble_sort(char *a, int n);

int main(void) {
    char a[10];
    int n = sizeof a / sizeof a[10];
    int i;
    char inname;
    char outname;

    printf("Enter input name: ");
    scanf("%s", &inname);
    printf("Enter output name: ");
    scanf("%s", &outname);

    FILE *in, *out;

    out = fopen(&outname, "w");

    if ((in = fopen(&inname, "r")) == NULL) {
        printf("File not found\n");

    }


    else {
        for (int i = 0; i < 10; i++)
        {
            fscanf(in, "%s ", &a[i]);
        }

        bubble_sort(a, n);

        for (i = 0; i < 10; i++) {
            printf("%s\n", a[i]);
            fprintf(out, "%s\n", a[i]);
        }
    }

        fclose(in);
        fclose(out);
        return 0;
    }


int bubble_sort(char *a, int n) {
    int i, j;
    char temp;

        for (j = 1; j<n; j++)
        {
            for (i = 0; i<n - j; i++)
            {
                if ((int)a[i] >= (int)a[i + 1])
                {
                    temp = a[i];
                    a[i] = a[i + 1];
                    a[i + 1] = temp;

            }
        }
    }
    return a[i];
}

Upvotes: 0

Views: 525

Answers (1)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

The basic problem, as I can see, is with

scanf("%s", &inname);

In your code, inname is a single char, which cannot hold string inputs. You'll be needing an array.

You need to change

char inname;
char outname;

to

#define NAMSIZ 32

char inname[NAMSIZ] = {0};
char outname[NAMSIZ] = {0};

and then,

scanf("%31s", inname);

and accordingly.

Same problem exist with fscanf(in, "%s ", &a[i]);, too.

Upvotes: 2

Related Questions