英文文章单词正确性检查程序(C语言实现)
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h>
#define MAX_WORD_LEN 50 #define MAX_WORDS 1000
int cmp(const void *a, const void b) { return strcmp((char **)a, *(char **)b); }
int main() { // 读取单词索引表 char *words[MAX_WORDS]; int n = 0; FILE *index_file = fopen('index.txt', 'r'); if (index_file == NULL) { printf('Failed to open index file. '); return 1; } char word[MAX_WORD_LEN + 1]; while (fgets(word, MAX_WORD_LEN + 1, index_file) != NULL) { // 去掉换行符 word[strcspn(word, '\n')] = '\0'; // 转换为小写 for (int i = 0; word[i]; i++) { word[i] = tolower(word[i]); } words[n] = malloc(strlen(word) + 1); strcpy(words[n], word); n++; } fclose(index_file); // 排序单词索引表 qsort(words, n, sizeof(char *), cmp);
// 读取文章并检查单词
FILE *input_file = fopen('in.txt', 'r');
if (input_file == NULL) {
printf('Failed to open input file.
'); return 1; } FILE *output_file = fopen('error.txt', 'w'); if (output_file == NULL) { printf('Failed to open output file. '); return 1; } char c; char word_buffer[MAX_WORD_LEN + 1]; int word_len = 0; int word_start = 0; while ((c = fgetc(input_file)) != EOF) { if (isalpha(c)) { if (word_len == 0) { word_start = ftell(input_file) - 1; } if (word_len < MAX_WORD_LEN) { word_buffer[word_len] = tolower(c); word_len++; } } else { if (word_len > 0) { // 检查单词是否在索引表中 word_buffer[word_len] = '\0'; int found = 0; int left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; int cmp_result = strcmp(word_buffer, words[mid]); if (cmp_result == 0) { found = 1; break; } else if (cmp_result < 0) { right = mid - 1; } else { left = mid + 1; } } if (!found) { // 输出错误单词 fseek(input_file, word_start, SEEK_SET); for (int i = 0; i < word_len; i++) { fprintf(output_file, '%c', fgetc(input_file)); } fprintf(output_file, '\n'); } word_len = 0; } } } fclose(input_file); fclose(output_file);
// 释放内存
for (int i = 0; i < n; i++) {
free(words[i]);
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/gmCN 著作权归作者所有。请勿转载和采集!