Hello everyone~!
I have a text file with integers on every line like:

2397
4013
9382
5995
4961
9961
1535
146
8153
3877
5872
2690
9731
8060
8452
7873
1109
4152
7256
2437
6815
2032
2473
1090
5674
6096
7868
422

My problem is: Im not sure how to store the information so i can sort it. I was able to get the information out of the txt file but when i sort it, the sort does not work. (the way i got the information is bad?)

 char temp[50] = {0};
    //get input store it in the array
          //array should be filled
          for(i=0;i<sizeof(sortArray);i++)
          {
              while(!feof(inFile))
              {
               fgets(temp,sizeof(temp),inFile);
                strcat(sortArray,temp);
              }
          }

Where do i start?

Dani AI

Generated

— your instinct is correct: store the values as integers and parse each line into an int instead of concatenating text. Concatenating with strcat produces a big string, and any sort done on those strings will be lexicographic (so "1090" can come before "422"). Also avoid while(!feof(...)) and relying on sizeof to count elements — both are common sources of bugs.

A simple, robust workflow:

  • Open the file.
  • Read one number at a time, checking the read function's return value.
  • Append into a dynamically grown int array (use realloc if you don’t know the count).
  • Sort with qsort using an int comparator.
  • Print or write results and free memory.

Example implementation (concise, production-ready checks omitted for brevity):

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

int cmp_int(const void *a, const void *b) {
    int ia = *(const int*)a, ib = *(const int*)b;
    return (ia > ib) - (ia < ib);
}

/* read ints, grow buffer, sort, print */
int main(void) {
    FILE *f = fopen("numbers.txt","r");
    if (!f) return 1;
    int cap = 128, n = 0, *arr = malloc(cap * sizeof *arr);
    int x;
    while (fscanf(f, "%d", &x) == 1) {
        if (n == cap) { cap *= 2; arr = realloc(arr, cap * sizeof *arr); }
        arr[n++] = x;
    }
    fclose(f);
    qsort(arr, n, sizeof *arr, cmp_int);
    for (int i = 0; i < n; ++i) printf("%d\n", arr[i]);
    free(arr);
    return 0;
}

Troubleshooting tips: test the reader by printing values immediately after reading; check realloc/malloc failures; use fgets + strtol when you need stricter error checking or to detect malformed lines; use long long/strtoll if numbers may exceed int. Following this pattern will fix the sort failures caused by treating numeric data as a single text blob.

I should use an integer array, and then use fscanf for to get input?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.