zoukankan      html  css  js  c++  java
  • 变位词实现 编程珠玑一处错误

    书中只实现了单词内部的排序而求得标记词,而并未实现单词之间的排序,所以运行结果按不符合作者预期结果,可能是作者的一个疏忽。

    完善后代码如下:

    #include <stdio.h>
    #include <string.h>
    #define WORD_MAX_LENGTH 100
    #define DICT_NUM 100

    char word[DICT_NUM][WORD_MAX_LENGTH], word_sign[DICT_NUM][WORD_MAX_LENGTH], old_word_sign[WORD_MAX_LENGTH];
    int count = 0;

    int char_cmp(char *x, char *y)
    {
    return *x - *y;
    }

    int str_compare(char *x, char *y )
    {
    return strcmp(x,y);
    }

    int sign_and_sort(char *input_file_name, char *output_file_name)
    {
    FILE *fp_input, *fp_output;
    int i = 0;
    if ((fp_input = fopen(input_file_name, "r")) == NULL || (fp_output = fopen(output_file_name, "w")) == NULL)
    {
    printf("cannot access the file!");
    exit(0);
    }

    while (fscanf(fp_input, "%s", word[count]) != EOF)
    {
    strcpy(word_sign[count], word[count]);
    qsort(word_sign[count], strlen(word_sign[count]),sizeof(char), char_cmp);
    strcat(word_sign[count], ": ");
    strcat(word_sign[count], word[count]);
    count++;
    }

    qsort(word_sign, count,sizeof(word_sign[count]), str_compare);
    for (i = 0;i < count; i++)
    fprintf(fp_output,"%s\n", word_sign[i]);

    fclose(fp_input);
    fclose(fp_output);
    return 0;
    }

    int squash(char *input_file_name, char *output_file_name)
    {
    FILE *fp_input, *fp_output;
    int linenumber = 0;
    count = 0;
    strcpy(old_word_sign, "");
    if ((fp_input = fopen(input_file_name, "r")) == NULL || (fp_output = fopen(output_file_name, "w")) == NULL)
    {
    printf("cannot access the file!");
    exit(0);
    }

    while (fscanf(fp_input, "%s %s", word_sign[count], word[count]) != EOF)
    {
    if (strcmp(old_word_sign, word_sign[count]) != 0 && linenumber > 0)
    fprintf(fp_output, "\n");
    strcpy(old_word_sign, word_sign[count]);
    linenumber++;
    fprintf(fp_output, "%s ", word[count++]);
    }

    fclose(fp_input);
    fclose(fp_output);
    return 0;
    }

    int main()
    {
    sign_and_sort("dict.txt", "mid.txt");
    squash("mid.txt", "result.txt");
    return 0;
    }

    运行过程及结果:



  • 相关阅读:
    日期比较
    Hashtable哈希表和SortedList排序列表类[转贴]
    XML读取数据
    列表效果,附上字数过多,将列表布局损坏
    event.keycode值大全[转帖]
    常用正则表达式
    写在d2沙龙之前的话
    物理引擎demo (4) —— 力、关节和马达
    基于向量的运动
    物理引擎demo (2) —— 拖拽
  • 原文地址:https://www.cnblogs.com/seebro/p/2375644.html
Copyright © 2011-2022 走看看