mercredi 23 février 2022

How to grab a user ID from user input and store as a value in a hashtable C++

I am having trouble understanding how to add a userid that the user inputs from command line into a hash table. I have already written the hash table and know it might need editing to do this and I have read that setting an array might work but the issue is that I use the insertion function for the hash table but once I leave the function that grabs the user input it disappears and now the has table is empty. I get that I might need to return something and the function that grabs the user input returns nothing at the moment. I am just confused and Google is not helping for the past 3 hours. Either posting here will help or ill get downvoted, worth a shot.

There are 3 files, the main function is in main.cpp, I have a header file, and a hashtable.cpp file. The insertion function in hashtable.cpp looks like this:

void hash_table::insertion(int key, string value)
{
    int hash_value = hash_function(key);
    auto& cell = table[hash_value];
    auto bItr = begin(cell);
    bool key_exists = false;

    for(;bItr != end(cell); bItr++)
    {
        if (bItr->first == key)
        {
            key_exists = true;
            bItr->second = value;
            cout << "[WARNING] Key exists. Value has been replaced." << endl;
            break;
        }
    }

    if(!key_exists)
    {
        cell.emplace_back(key, value);
    }
    else 
    {
        return;
    }

}

Cool, so I should be able to do this in another function:

hash_table HT;

    int hash_id = random_number();

    cout << "Enter your preferred username: \n";
    cin >> r_user;

    cout << "Enter your preferred password: \n";
    cin >> r_password;

    //inserts the randomly generated ID for the user and the password into the hash table
    HT.insertion(hash_id, r_password);

    //gives the user thier unique user ID by printing to the console
    cout << "[IMPORTANT] Your ID is: " << hash_id << "\n";

    //use the stream to append the username and password to the records file 
    ofstream f1("records.txt", ios::app);
    f1 << hash_id << ' ' << r_user << ' ' << r_password << endl;

    cout << "Your registration was successful! \n";

    HT.print_table();

    main();

I know that the hash_id should be left to be random generated, I just haven't implemented that yet. Even so I can't think of how to get the users id from the input into the table. When the function goes back to main(); there is no longer anything in the table anymore. I have tried making the function with int,string parameters and then returning but that is also not helping. Any suggestions? I am not looking for you guys to do homework for me I am just 100% stuck and need a push. I am still learning C++ (by force). Let me know if there is needed clarification, sorry for the excessive explanation.

Aucun commentaire:

Enregistrer un commentaire