怎样将许多单词按字典顺序排列
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE*fp;
char str[3][10],temp[10];
int i,j,k,n=3;
printf("Enter strings:\n");
for(i=0;i<n;i++)
gets(str[i]);
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
{
if(strcmp(str[k],str[j])>0)
k=j;
if(k!=i)
{
strcpy(temp,str[i]);
strcpy(str[i],str[k]);
strcpy(str[k],temp);
}}
}
if((fp=fopen("String.dat","w"))==NULL)
{
printf("cannot open file!\n");
exit(0);
}
printf("\nThe new sequence:\n");
for(i=0;i<n;i++)
{
fputs(str[i],fp);fputs("\n",fp);
printf("%s\n",str[i]);
}
return 0;
}
书本上有提供这些代码。
还说如果要排10个字符串的话,把3改成10就行。
不过我试了一下,发现运行结果并不准确。
希望谁能帮我改改
[解决办法]
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE*fp;
char str[10][10],temp[10];
int i,j,k,n=10;
printf("Enter strings:\n");
for(i=0;i<n;i++)
gets(str[i]);
for(i=0;i<n-1;i++)
{
k=i;
for(j=i+1;j<n;j++)
{
if(strcmp(str[k],str[j])>0)
k=j;} \\加了个"}"
if(k!=i)
{
strcpy(temp,str[i]);
strcpy(str[i],str[k]);
strcpy(str[k],temp);
}} \\删掉"}"
if((fp=fopen("String.dat","w"))==NULL)
{
printf("cannot open file!\n");
exit(0);
}
printf("\nThe new sequence:\n");
for(i=0;i<n;i++)
{
fputs(str[i],fp);fputs("\n",fp);
printf("%s\n",str[i]);
}
return 0;
}