C语言英文文章单词正确性检查

本程序利用预设的单词索引表(index.txt)对英文文章(in.txt)进行单词正确性检查。若文章中出现不在索引表中的单词,则将其输出到 error.txt 文件中。

假设条件:

  1. in.txt 中的文章格式可能杂乱无章,且可能不完整。2. index.txt 中的单词数量不超过 1000 个,每个单词长度不超过 50 个字母。3. 错误单词可多次出现,并会输出多次。

实现步骤:

  1. 读取 index.txt 文件,将所有单词存储到 set 容器中,set 容器可以自动去重并按字典序排序。2. 读取 in.txt 文件,逐个字符判断是否为字母。 - 如果是字母,则将其添加到当前单词中。 - 如果不是字母,则判断当前单词是否在 set 容器中: - 如果不在,则将该单词添加到 set 容器中。3. 将 set 容器中的所有单词按照字典序输出到 error.txt 文件中。

**代码实现:**c#include <stdio.h>#include <string.h>#include <ctype.h>#include #include

using namespace std;

int main() { // 打开索引表文件 ifstream indexFile('index.txt'); if (!indexFile.is_open()) { perror('打开 index.txt 文件失败'); return 1; }

// 读取索引表文件中的单词,并存储到 set 容器中    set<string> wordSet;    string word;    while (getline(indexFile, word)) {        wordSet.insert(word);    }    indexFile.close();

// 打开英文文章文件    ifstream inFile('in.txt');    if (!inFile.is_open()) {        perror('打开 in.txt 文件失败');        return 1;    }

// 打开错误单词输出文件    ofstream errorFile('error.txt');    if (!errorFile.is_open()) {        perror('打开 error.txt 文件失败');        return 1;    }

// 读取英文文章文件中的内容,并逐个字符判断是否为字母    char ch;    string currentWord;    while (inFile.get(ch)) {        if (isalpha(ch)) {            currentWord += tolower(ch); // 将字母转换为小写        } else {            // 判断当前单词是否为错误单词            if (!wordSet.count(currentWord) && !currentWord.empty()) {                // 将错误单词输出到 error.txt 文件中                errorFile << currentWord << endl;            }            currentWord.clear(); // 清空当前单词        }    }

// 处理最后一个单词    if (!wordSet.count(currentWord) && !currentWord.empty()) {        errorFile << currentWord << endl;    }

inFile.close();    errorFile.close();

return 0;}

代码说明:

  • 使用 set 容器存储单词,可以自动去重并按字典序排序。- 使用 ifstreamofstream 类来读取和写入文件。- 使用 isalpha() 函数判断字符是否为字母。- 使用 tolower() 函数将字母转换为小写。- 使用 count() 函数判断单词是否存在于 set 容器中。

运行结果:

程序运行后,会将所有在 in.txt 中出现,但不在 index.txt 中的单词,按字典序输出到 error.txt 文件中。

C语言英文文章单词正确性检查

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

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