c - 按字母顺序列出 C 中的列表?
问题描述
该程序收到以下列表:
Google
Apple
Microsoft
Samsung
我想按字母顺序排序。
我编写了以下程序,但在运行时出现分段错误。
#include<stdio.h>
#include<string.h>
int main()
{
char a[20][20],str[20];
int i;
FILE *file;
file=fopen("./test.txt","r");
if(file == NULL)
printf("FILE NOT Opened...\n");
for(i=0;i<5;i++)
{
if(fgets(str, 20, file) != NULL)
{
strcpy(a[i], str);
printf("%s",a[i]);
}
}
char *tmp;
tmp = malloc(20); // still same error
int j;
for(i=0; a[i]; i++) {
for(j = 0; a[j]; j++) {
if(strcmp(a[i], a[j]) < 0) {
strcpy(tmp,a[i]);
strcpy(a[i],a[j]);
strcpy(a[j],tmp);
}
}
}
for(i = 0; a[i]; i++) printf("%s\n", a[i]);
return 0;
}
解决方案
As bruceg suggested, your for
loops need work. And, you may want to strip the newline.
Also, keep a count of the number of lines.
I've also done some further cleanup:
#include <stdio.h>
#include <string.h>
#define NLINES 20
#define LWID 20
int
main()
{
char a[NLINES][LWID];
char tmp[LWID];
char *cp;
int count;
int i;
int j;
FILE *file;
file = fopen("./test.txt", "r");
if (file == NULL)
printf("FILE NOT Opened...\n");
for (count = 0; count < NLINES; count++) {
if (fgets(tmp, LWID, file) == NULL)
break;
cp = strchr(tmp,'\n');
if (cp != NULL)
*cp = 0;
strcpy(a[count], tmp);
printf(" %s", a[count]);
}
printf("\n");
fclose(file);
for (i = 0; i < count; i++) {
for (j = 0; j < count; j++) {
if (strcmp(a[i], a[j]) < 0) {
strcpy(tmp, a[i]);
strcpy(a[i], a[j]);
strcpy(a[j], tmp);
}
}
}
for (i = 0; i < count; i++)
printf("%s\n", a[i]);
return 0;
}
Here is the output:
Google Apple Microsoft Samsung
Apple
Google
Microsoft
Samsung