这些是以下航班:
AA43 DFW DTW 2016-01-06 11:00
AA43 DFW DTW 2016-01-17 11:00
AA44 SEA JFK 2015-02-05 7:45
AA197 ORD BOS 2012-03-12 11:50
AA1 JFK LAX 2016-07-02 9:00
OO7435 DTW PLN 2016-11-22 21:55
F9612 DEN MIA 2014-12-19 22:15
DL801 GEG MSP 2016-08-31 9:00
DL1087 ATL DAB 2016-04-10 12:05
DL828 IAH SLC 2012-06-02 7:45
现在想象一下,如果所有这些航班都在文本文件中 . 你会如何按出发日期排序?当我的意思是“离开日期”时,我的意思是从“yyyy-mm-dd hr:min”中对它们进行排序 .
当我尝试对它进行排序时,它只会对航班的所有内容进行排序,而不仅仅是出发日期 . 如果没有航空公司航班但只是出发日期,它将完美排序 .
以下是我之前所说的代码 .
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
FILE *fp1;
FILE *fp2;
int i, j;
int line = 0;
char temp[128], outputFile[15], airLine[256];
char **strData = NULL;
printf("Enter input file name:");
scanf("%s", airLine);
fp1 = fopen(airLine,"r");
if (!fp1)
{
return 1;
}
sprintf(outputFile, "sun");
fp2 = fopen(outputFile, "w");
while(fgets(temp, 128, fp1))
{
if(strchr(temp, '\n'))
{
temp[strlen(temp-1)] = '\0';
strData = (char**)realloc(strData, sizeof(char**)*(line+1));
strData[line] = (char*)calloc(128, sizeof(char));
strcpy(strData[line], temp);
line++;
}
}
for(i= 0; i < (line - 1); ++i)
{
for(j = 0; j < ( line - i - 1); ++j)
{
if(strcmp(strData[j], strData[j+1]) > 0)
{
strcpy(temp, strData[j]);
strcpy(strData[j], strData[j+1]);
strcpy(strData[j+1], temp);
}
}
}
for(i = 0; i < line; i++)
{
fprintf(fp2,"%s\n",strData[i]);
}
for(i = 0; i < line; i++)
{
free(strData[i]);
}
free(strData);
fclose(fp1);
fclose(fp2);
return 0;
}
你怎么能按出发日期<yyyy-mm-dd hr:min>对上面列出的航班进行排序?
1 回答
这需要一些努力 .
通过存储指向结构的指针来创建元素表
创建可以按日期比较元素的函数(参见
man qsort
)进行比较的函数有两个参数(由
void *
指向) . 我们所要做的就是(在其中)将void *
强制转换为我们正在处理的类型的指针并比较值 .来源:http://www.gnu.org/software/libc/manual/html_node/Comparison-Functions.html
请注意这部分文档
qsort
排序元素