在文件中查找单词

Finding words in a file

本文关键字:单词 查找 文件      更新时间:2023-10-16

此函数构建读取文本输入的树(包含在argv[1]中命名的文件中)。然后,我打开文件,逐字符读取,如果有新行("if(token=='\n')"),请跟踪此行号,并将其存储在向量中,以便稍后访问。接下来,它将其分解为一系列单词(使用除数字或字母符号之外的任何字符作为终止符)。这就是我出错的地方。然后,我尝试将每个字符添加到字符串中,然后当标记是数字或字母符号时,将字符串推到向量中,以便稍后访问。我的逻辑正确吗?当把每个单词推到一个向量中时,你能帮我纠正错误吗。

对不起,如果混淆

BinarySearchTree buildTree (char *argv[]){
    ifstream file;
    vector<char *> V;
    int line = 0;
    vector<int> LineNumber;
    file.open(argv[1],ios::in);
    char token;
    string word[] = {};

    if (file.is_open()){
        token = file.get();//reads the next character from a stream
        if (token == 'n')
            line++;
        LineNumber.push_back(line);
        while (token!= ' ' || '0' || '1' || '2' || '3' || '4' || '5' ||'6' || '7' || '8' || '9'){
        //while character is not space, digit, or non-alphabetic character
            word += token;//adds character to string array *error here
        }
        V.push_back(word);//adds word to vector *error here
    }
}

这一行并没有做你认为它会做的事情:

while (token!= ' ' || '0' || '1' || '2' || '3' || '4' || '5' ||'6' || '7' || '8' || '9')

你必须单独比较,token != '0' && token != '1' ...。然而,您总是可以利用C标准库(这就是它的用途)

#include <cctype>
while (!std::isspace(token) && !std::isdigit(token))

另外,这里不需要while循环。将其更改为if

其次,您正在尝试将char连接到string[]。您可能打算声明一个string

std::string word = "";

最后,您的vector是用value_type char*声明的,但您正试图推回一个字符串。更改为:

std::vector<std::string> V;

以上内容纠正了代码中的即时错误,但可能没有解决核心问题。据我所知,你试图只找到由字母字符组成的字符串(没有数字、空格或标点符号)。你的条件只是变成if (std::isalpha(token)),因为这排除了其他三个。

其次,代码中没有循环。你只读了一个字符。您可以使用while (std::getline(file, input))逐行读取文件。由于流的性质,一旦流中没有其他可读取内容,循环就会终止。因此,您的代码变为:

if (file.is_open()){
    std::string input;
    while (std::getline(file, input))
    {
        for (std::size_t i = 0; i < input.size(); ++i)
        {
            token = input[i];
            if (token == 'n')
            {
                line++;
            }
            LineNumber.push_back(line);
            if (std::isalpha(token))
            {
                word += token;
            }
        }
        V.push_back(word);
        word = "";
    }
}

注意word = ""。在构建下一个单词之前,你需要将其留空。

此外,在将单词推入向量之前,您可能需要检查单词是否为空(以避免向量中出现空白条目):

if (word.size()) V.push_back(word);