#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>

#define MAX_WORD_LEN 50 // 单词最大长度 #define MAX_WORD_NUM 1000 // 单词最大数量

int cmp(const void *a, const void b) { return strcmp((char **)a, *(char **)b); }

int main() { char *words[MAX_WORD_NUM]; // 单词索引表 char word[MAX_WORD_LEN + 1]; // 读入的单词 int word_num = 0; // 单词数量 FILE *fp_index = fopen("index.txt", "r"); // 打开单词索引表文件 if (fp_index == NULL) { printf("index.txt not found!\n"); return 0; } // 读入单词索引表 while (fscanf(fp_index, "%s", word) != EOF) { // 转换为小写字母 for (int i = 0; word[i]; i++) { word[i] = tolower(word[i]); } words[word_num] = (char *)malloc(strlen(word) + 1); strcpy(words[word_num], word); word_num++; } fclose(fp_index); // 对单词索引表按字典序排序 qsort(words, word_num, sizeof(char *), cmp);

FILE *fp_in = fopen("in.txt", "r"); // 打开英文文章文件
FILE *fp_error = fopen("error.txt", "w"); // 打开错误单词输出文件
if (fp_in == NULL) {
    printf("in.txt not found!\n");
    return 0;
}
if (fp_error == NULL) {
    printf("error.txt cannot be created!\n");
    return 0;
}
// 读入英文文章
while (fscanf(fp_in, "%s", word) != EOF) {
    // 转换为小写字母
    for (int i = 0; word[i]; i++) {
        word[i] = tolower(word[i]);
    }
    // 在单词索引表中二分查找
    int left = 0, right = word_num - 1;
    while (left <= right) {
        int mid = (left + right) / 2;
        if (strcmp(words[mid], word) == 0) {
            break;
        } else if (strcmp(words[mid], word) < 0) {
            left = mid + 1;
        } else {
            right = mid - 1;
        }
    }
    // 如果单词不在索引表中,输出到错误单词输出文件
    if (left > right) {
        fprintf(fp_error, "%s\n", word);
    }
}
fclose(fp_in);
fclose(fp_error);
// 释放单词索引表内存
for (int i = 0; i < word_num; i++) {
    free(words[i]);
}
return 0;
首页current课程信息在线作业在线考试在线答疑 李思德 切换课程计算思维二王也 更多栏目 帮助 当前作业 第五次作业 - 06 历史作业 第四次作业 - 06 第三次作业 - 06 第二次作业 - 06 第一次作业 - 06 平台测试题目 - 不计入成绩 返回编程题列表12»第五次作业 - 06编程题1 单词检查【问题描述】已知有一个正确单词索引表保存在当前目录下的文件indextxt中且全

原文地址: http://www.cveoy.top/t/topic/d5jx 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录