Преобразование строки в char в c ++ - PullRequest
0 голосов
/ 24 октября 2019

Я пытаюсь создать валидатор проверки правописания с использованием Hash Table. У меня есть список слов в текстовом файле. Я хочу импортировать их в программу и ввести их в Hash Table, используя отдельную цепочку. Теперь я хочу запустить программу, и у меня есть эти две ошибки. Может кто-нибудь помочь мне с этим?

в строке 30 - нет соответствующей функции для вызова 'std :: __ cxx11 :: basic_string :: push_back (std :: __ cxx11 :: string &)'

в строке 40 - нет соответствия для оператора == (типы операндов: __gnu_cxx :: __ alloc_traits, char> :: value_type '{aka' char '} и' std :: __ cxx11 :: string '{aka 'std :: __ cxx11 :: basic_string'})

Я знаю, что это простая ошибка преобразования str в char, но я не мог понять, как это сделать, не изменяя остальную часть программы.

Я хотел бы иметь простое решение, которое не меняет существующий код. Если это невозможно, скажите, пожалуйста, как действовать.

#include<iostream>
#include <string>
#include <cstring>
#include <fstream>


std::string hashTable[27];
int hashTableSize = 27;
#define MAX_LEN 27
using namespace std;


int hashFunc(std::string s)
{
    // A simple hashing, no collision handled
    int sum=0,index=0;
    for(std::string::size_type i=0; i < s.length(); i++)
    {
        sum += s[i];
    }
    index = sum % MAX_LEN;
    return index;
}

void insert(std::string s)
{
    // Compute the index using Hash Function
    int index = hashFunc(s);
    // Insert the element in the linked list at the particular index
    hashTable[index].push_back(s);
    }

void search(string s)
{
    //Compute the index by using the hash function
    int index = hashFunc(s);
    //Search the linked list at that specific index
    for(int i = 0;i < hashTable[index].size();i++)
    {
        if(hashTable[index][i] == s)
        {
            cout << s << " is found!" << endl;
            return;
        }
    }
    cout << s << " is not found!" << endl;
}
int main(){


    //opening text file
    std::ifstream inFile;
    inFile.open("un.txt");

    // If text file doesnot exist or not included in root folder.
    if(inFile.fail()) {

        std::cerr << "Error opening file"<< std::endl ;

        exit(1);
    }

    //if text file exists.
    std::string wordsinfile;
    std::string words[100];
    int count=0,i=0;
    std::string str;


    // writing words from text file into Array.
    while( !inFile.eof()) {
        inFile >> wordsinfile;
        words[i]=wordsinfile;
        count++;
        i++;
    }

    for (i=0;i<100;i++){
        std::cout<< words[i]<<std::endl;
    }


    for(i=0;i<=23;i++) {
        insert(words[i]);
    }


    int choice;
    string z;
    string y;
    while(1) {

        cout << "Enter choice. 1) Insert\n 2) Search\n 3) Exit\n";
        cin >> choice;
        switch (choice) {
            case 1:
                cin>>y;
                insert(y);
                break;
            case 2:

                cin>>z;
                search(z);
                break;
            case 3:
                exit(0);
        }
    }
    return 0;
}

В моем текстовом файле было 38 разных слов, а размер хеш-таблицы равен 27

1 Ответ

0 голосов
/ 24 октября 2019

Вот правильная версия вашей программы. Предполагается, что ваша хеш-таблица представляет собой набор строк, и, поскольку вы используете индексирование в функции поиска, использование вектора STL для хеш-таблицы должно помочь.

#include <iostream>
#include <string>
#include <cstring>
#include <fstream>
#include <vector>

std::vector<std::string> hashTable[27];
int hashTableSize = 27;
#define MAX_LEN 27
using namespace std;


int hashFunc(std::string s)
{
    // A simple hashing, no collision handled
    int sum=0,index=0;
    for(std::string::size_type i=0; i < s.length(); i++)
    {
        sum += s[i];
    }
    index = sum % MAX_LEN;
    return index;
}

void insert(std::string s)
{
    // Compute the index using Hash Function
    int index = hashFunc(s);
    // Insert the element in the linked list at the particular index
    hashTable[index].push_back(s);
    }

void search(string s)
{
    //Compute the index by using the hash function
    int index = hashFunc(s);
    //Search the linked list at that specific index
    for(int i = 0;i < hashTable[index].size();i++)
    {
        if(hashTable[index][i] == s)
        {
            cout << s << " is found!" << endl;
            return;
        }
    }
    cout << s << " is not found!" << endl;
}

int main(){
    //opening text file
    std::ifstream inFile;
    inFile.open("un.txt");

    // If text file doesnot exist or not included in root folder.
    if(inFile.fail()) {

        std::cerr << "Error opening file"<< std::endl ;

        exit(1);
    }

    //if text file exists.
    std::string wordsinfile;
    std::vector<std::string> words;
    std::string str;


    // writing words from text file into Array.
    while( inFile >> wordsinfile) {
        words.push_back(std::move(wordsinfile));
    }

    std::cout << "Total words read: " << words.size() << std::endl;

    for (int i = 0;i < words.size(); i++){
        std::cout << words[i] << std::endl;
    }


    for(int i=0; i < words.size(); i++) {
        insert(words[i]);
    }


    int choice;
    string z;
    string y;
    while(1) {

        cout << "Enter choice. 1) Insert\n 2) Search\n 3) Exit\n";
        cin >> choice;
        switch (choice) {
            case 1:
                cin>>y;
                insert(y);
                break;
            case 2:

                cin>>z;
                search(z);
                break;
            case 3:
                exit(0);
        }
    }
    return 0;
}
...