C语言实现英文文章单词拼写检查工具
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h>
#define MAX_WORD_LEN 50 #define MAX_INDEX_SIZE 1000
int main() { // 读取单词索引表 char index[MAX_INDEX_SIZE][MAX_WORD_LEN+1]; int index_size = 0; FILE* index_file = fopen('index.txt', 'r'); if (index_file == NULL) { printf('Failed to open index file.\n'); return 1; } while (fgets(index[index_size], MAX_WORD_LEN+1, index_file) != NULL) { // 去掉行末换行符 index[index_size][strcspn(index[index_size], '\n')] = '\0'; index_size++; } fclose(index_file);
// 读取英文文章并检查单词正确性
char word[MAX_WORD_LEN+1];
int word_len = 0;
FILE* in_file = fopen('in.txt', 'r');
FILE* error_file = fopen('error.txt', 'w');
if (in_file == NULL || error_file == NULL) {
printf('Failed to open input or error file.\n');
return 1;
}
int c;
while ((c = fgetc(in_file)) != EOF) {
if (isalpha(c)) {
// 当前字符是字母,加入单词
if (word_len < MAX_WORD_LEN) {
word[word_len++] = tolower(c);
}
} else {
// 当前字符不是字母,结束单词
if (word_len > 0) {
word[word_len] = '\0';
// 在索引表中查找单词
int found = 0;
for (int i = 0; i < index_size; i++) {
if (strcmp(word, index[i]) == 0) {
found = 1;
break;
}
}
if (!found) {
// 单词不在索引表中,输出到错误文件
fprintf(error_file, '%s\n', word);
}
word_len = 0;
}
}
}
fclose(in_file);
fclose(error_file);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/gmGs 著作权归作者所有。请勿转载和采集!