首页 > 解决方案 > 为什么文本文件中的字符串没有添加到我的字符串数组中?

问题描述

我有一个程序应该采用 Dictionary.txt——它有 200 行单独的行,每行一个字符串——并将每个字符串散列到一个数组中。然后我获取用户输入的字符串并尝试在我新填充的数组中找到该字符串。该程序使用模哈希函数来获取每个字符串的数组索引,并且应该逐行读取 .txt 文件。截至目前,程序执行没有错误,但在尝试读取字符串后数组完全为空。

我已经尝试过 getline 函数以及文件 >> 输入。

编辑:我的文件没有正确打开,所以我将我的 file.open() 方法中的 url 替换为 C:/ 直接 url,而不是使用我包含在我的 Visual Studio 项目中的那个。

int wordFinder(fstream& file, string word) {
    string Table[200];
    for (int i = 0; i < 200; i++) {
        //modulo hashing using size of array
        int index = i % 200;
        //collision
        if (!(Table[index].empty())) {
            int count = 0;
            do {
                index = (index + 1) % 200;
                count++;
            } while ((!(Table[index].empty())) && (count < 200));//while the current position is occupied and count is less than the size of the array
            getline(file, Table[index], '\n');//take string from file and put it into the table array
            cout << "Collision " << Table[index]<< endl;
        }
        //no collision
        else {
            cout << "No Collision " << Table[index]<<index<< endl;
            getline(file, Table[index], '\n');//take string from file and put it into the table array
        }
    }
    //find string if in array
    for (int i = 0; i < 200; i++) {
        if (Table[i].compare(word) == 0) {
            return 1;
        }
    }
    //print table values
    for (int i = 0; i < 200; i++) {
        cout << Table[i] << endl;
    }
    return 0;
}

如果找到该单词,则程序的预期结果是返回 1,如果未找到,则返回 0。它还应该打印值数组,每个索引都有一个来自 .txt 文件的单独单词。到目前为止,程序总是返回 0,因为数组最终完全是空的,因此程序会打印一堆空白。

标签: c++hashfind

解决方案


我的文件未正确打开,因此我将 file.open() 方法中的 url 替换为 C:/ 直接 url,而不是使用我在 Visual Studio 项目中包含的那个。在我进行此更改后它起作用了。


推荐阅读