【发布时间】:2016-02-08 13:40:35
【问题描述】:
我有一个问题,我的 C 语言程序必须找到有 N 个字母的单词,计算它们并按字典顺序对它们进行排序,然后将它们保存到另一个文件中。如何按字母顺序对单词进行排序?
这是我的代码:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <stddef.h>
#include <string.h>
int main()
{
FILE *r, *fp;
char ch[100],t[100];
int n,i,j,x=0;
r=fopen("text.txt","r");
fp=fopen("text2.txt","w");
fgets(ch, 100, r);
char *start;
int len;
char *s = ch;
char *p = s;
printf("Give the length of word: ");
scanf("%d",&n);
printf("\n\nWords with %d letters: \n\n",n);
while (*p) {
while (*p && isspace(*p))
++p;
start = p;
while (*p && !isspace(*p))
++p;
len = p - start;
if (len == n) {
printf("%.*s\n", len, start);
x++;
fprintf(fp,"%.*s",len, start);
}
}
printf("\nNumber of words: %d ",x);
fclose(fp);
getch();
fclose(r);
}
【问题讨论】:
-
实现自己的排序功能