0

所以任务是打开一个文本文件(没有 fopen,只使用终端/控制台中的命令),将信息放入数组中,对数组进行排序(数字最初是随机顺序“4,12,2,4”)和然后所有排序的数据必须打印在第二个txt文件上。现在我自己做了一个程序,但显然不正确,你能告诉我我错在哪里,我是第一次使用qsort,所以我不是专家这个,以前用过冒泡排序,先谢谢了!!

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

//first time using qsort function.
int array[1024];
int array_counter=0;

int compare (const void * num1, const void * num2)
{
   return (*(int*)num1 - *(int*)num2);
}

int main ()
{
   int i;
   char c;
   while((c=getchar())!=EOF)
   {
      if(c >='0' && c <='9' )
      {
         i = atoi(&c);
         array[array_counter] = i;
         array_counter++;
      }
   }
   int counter;
   qsort(array, array_counter, sizeof(array[array_counter]), compare);
   for(counter = 0; counter < array_counter; counter++)
   {
   printf ("%d", array[array_counter]);
   }
   return 0;
}
4

2 回答 2

0

我在你的代码中发现了几个错误,所以这里是带有解释的工作代码(参见qsort的手册页)

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

//first time using qsort function.
int array[1024];
int array_counter=0;

int compare (const void * num1, const void * num2)
{
   return (*(int*)num1 - *(int*)num2);
}

int main ()
{
   int i;
   char c;
   // use '0' terminated string  for passing it to atoi as this is what it is expecting
   // not only a pointer to char
   char buf[2];
   buf[1] = '\0'; // terminate the string with a '0' since you want only to have digits in your buffer
   // you may use something else (scanf for example) to read number of more than one digit)
   while((c=getchar())!=EOF)
   {
      if(c >='0' && c <='9' )
      {
         // put the char in buf
         buf[0] = c;
         // pass that buf to atoi (even if &c is satisfiying the signature of atoi it is not null terminated)
         i = atoi(buf);
         array[array_counter] = i;
         array_counter++;
      }
   }

   // arguments passed to qsort were wrong (second and third)
   // first is the array (or where the sorting should start)
   // second is the size of one element in the array thus sizof(int)
   // third is the number of the array elements to be sorted
   // the compare function
   qsort(array, sizeof(int), array_counter, compare);

   int counter;
   for(counter = 0; counter < array_counter; counter++)
   {
       // use counter to access array elements not array_counter, array_counter ist the index of the next free element and is always 0
       printf ("%d ", array[counter]);
   }
   return 0;
}

示例文本文件digits.txt

2 1 6 4 

执行命令

out.exe < digits.txt

输出

1 2 4 6
于 2013-04-07T21:22:03.103 回答
0
   while((c=getchar())!=EOF)
   {
      if(c >='0' && c <='9' )
      {
         i = atoi(&c);
         array[array_counter] = i;
         array_counter++;
      }
   }

这是错误的。您需要将字符放入缓冲区,以空值终止它,然后调用atoi缓冲区。或者你可以使用scanf而不是你自己的循环;

printf ("%d", array[array_counter]);

你想要“%d\n”,否则数字将被挤在一起。

法官说这是错误的答案

如果您在提交之前进行了一些测试,您就会知道这是错误的答案......检查您放入数组的数字是否具有正确的值,然后检查输出是否正确。

于 2013-04-07T21:00:25.690 回答