0

So i have a file called output.txt which contains a list of numbers (12365 25460 12522 22707 8714 28771 235 11401 25150 26342 0) and i want to take them and pass them through my selection sort, ive managed to open the file and read them into my program but instead when the selction sort fiishes it comes out with a list of numbers that have nothing to do with my input (although they are in order as they should be)

#include <stdio.h>
int main() {
   FILE *outp;
   char arr[10];
   outp = fopen("output.txt", "r");
   if (outp == NULL)
   {
      puts("Issue in opening the input file");
   }

   while(1)
   {
      if(fgets(arr, 10, outp) ==NULL)
         break;
      else
         printf("%s", arr);
   }
   fclose(outp);

   int n=10;
   int i, j, position, swap;
   for (i = 0; i < (n - 1); i++) {
      position = i;
      for (j = i + 1; j < n; j++) {
         if (arr[position] > arr[j])
            position = j;
         }
         if (position != i) {
            swap = arr[i];
            arr[i] = arr[position];
            arr[position] = swap;
         }
   }
   for (i = 0; i < n; i++)
      printf("%d\n", arr[i]);
   return 0;
}
5
  • arr is an array of 10 characters, not 10 numbers. Commented Jan 1, 2021 at 20:34
  • so what would i use instead? @Barmar Commented Jan 1, 2021 at 20:37
  • You're just reading the first 10 characters in the file, and each element of arr is their character codes. Commented Jan 1, 2021 at 20:37
  • 1
    Use int arr[10]; and then read them with fscanf(). Commented Jan 1, 2021 at 20:37
  • in which part of the code? becasue i already have char arr[10] at the top... Commented Jan 1, 2021 at 20:39

1 Answer 1

1

You're just reading the first 10 characters in the file, and setting the elements of arr to their character codes.

You need to parse the file contents as integers.

int arr[10];
for (i = 0; i < 10; i++) {
    fscanf(outp, "%d", &arr[i]);
}
Sign up to request clarification or add additional context in comments.

5 Comments

okay this helps definetly but doing this gives me conflicting types for 'arr'
Conflicting with what? You should only declare the variable once.
This should replace how you declared it, not be in addition.
so this should replace the line 'Char arr[10]' sorry got confused for a second
Of course. char can only hold numbers up to 127 or 255 (depending on whether it's signed or unsigned).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.