为什么我的选择排序输出与我的输入不同

  • 本文关键字:排序 选择 输出 c
  • 更新时间 :
  • 英文 :


所以我有一个名为output.txt的文件,其中包含一个数字列表(12365 25460 12522 22707 8714 28771 235 11401 25150 26342 0(,我想把它们通过我的选择排序,我设法打开了文件并将其读取到我的程序中,但当选择排序失败时,它会显示一个与我的输入无关的数字列表(尽管它们按顺序排列(

#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("%dn", arr[i]);
return 0;
}

您只需读取文件中的前10个字符,并将arr的元素设置为其字符代码。

您需要将文件内容解析为整数。

int arr[10];
for (i = 0; i < 10; i++) {
fscanf(outp, "%d", &arr[i]);
}

最新更新