C语言实现英文文章单词正确性检查
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.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]; int word_num = 0; FILE *index_file = fopen('index.txt', 'r'); if (index_file == NULL) { printf('Failed to open index file.\n'); return 1; } char word[MAX_WORD_LEN + 1]; while (fscanf(index_file, '%s', word) == 1) { words[word_num] = strdup(word); word_num++; } fclose(index_file); // 排序单词索引表 qsort(words, word_num, sizeof(char *), cmp); // 读取英文文章并进行单词检查 FILE *input_file = fopen('in.txt', 'r'); if (input_file == NULL) { printf('Failed to open input file.\n'); return 1; } FILE *output_file = fopen('error.txt', 'w'); if (output_file == NULL) { printf('Failed to open output file.\n'); return 1; } char c; char cur_word[MAX_WORD_LEN + 1]; int cur_word_len = 0; while ((c = fgetc(input_file)) != EOF) { if (isalpha(c)) { cur_word[cur_word_len] = tolower(c); cur_word_len++; } else { if (cur_word_len > 0) { cur_word[cur_word_len] = '\0'; int found = 0; for (int i = 0; i < word_num; i++) { if (strcmp(words[i], cur_word) == 0) { found = 1; break; } } if (!found) { fprintf(output_file, '%s\n', cur_word); } cur_word_len = 0; } } } // 处理最后一个单词 if (cur_word_len > 0) { cur_word[cur_word_len] = '\0'; int found = 0; for (int i = 0; i < word_num; i++) { if (strcmp(words[i], cur_word) == 0) { found = 1; break; } } if (!found) { fprintf(output_file, '%s\n', cur_word); } } fclose(input_file); fclose(output_file); // 释放内存 for (int i = 0; i < word_num; i++) { free(words[i]); } return 0; }
原文地址: https://www.cveoy.top/t/topic/gmJb 著作权归作者所有。请勿转载和采集!