所以任务是打开一个文本文件(WITHOUT 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;
}
答案 0 :(得分: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”,否则这些数字会一起被粉碎。
法官说这是错误的答案
如果您在提交之前进行了一些测试,您会知道这是错误的答案...检查您放入数组的数字是否具有正确的值,然后检查输出是否正确。
答案 1 :(得分: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