Read access violation when running my program

I am creating a simple Bank system in c++ to test my knowledge since I’m a beginner. I am having trouble with writing data to a private class, and after looking around on the internet I came up with a solution that I thought would work but doesn’t. There is an exception thrown when I finish the “Creating a user” part which says “Exception thrown: read access violation._Pnext was 0x6“. I’m not sure what this means, but my guess is that it has something to do with the pointers in the createuser function. I hope I’m not too vague in my explanation here, but I have absolutely no idea what is happening. Also, any criticism is welcome.

#include <iostream>
#include <string>


void clearscreen();
int createuser();
class MyClass
{
private:
    std::string Username;
    std::string Password;
    int money = 0;

public:
    void setUsername(std::string x) {
        Username = x;
    }
    void setPassword(std::string y) {
        Password = y;
    }
    void setMoney(int z) {
        money = z;
    }
};
void clearscreen() {
    system("cls");

}

int main() {
    std::cout << "Welcome new User!n" << std::endl;
    bool exitprogram = false;
    while (exitprogram == false)
    {
        std::cout << "The Options are:n";
        std::cout << "1.  Create Usern" << "2.  Loginn" << "3.  Exit Programn" << "nEnter an option: ";
        int option = 0;
        std::cin >> option;
        switch (option)
        {
        case 1:
            createuser();
            break;
        case 2:
            std::cout << "nThis option is not avalible yet!";
        case 3:
            exitprogram = true;
            break;
        }
    }
    


    return 0;
}


int createuser() {

    clearscreen();
    MyClass User;
    int* p = (int*)&User;
    std::string* i = (std::string*)&User;
    std::cout << "Please enter the correct information!n" << "Username: ";
    std::string createusern;
    std::cin >> createusern;
    *i = createusern;
    std::cout << "n Password: ";
    std::string createpasswordn;
    std::cin >> createpasswordn;
    *i = createpasswordn;
    std::cout << "nDeposit Money: ";
    int insertmoney;
    std::cin >> insertmoney;
    *p = insertmoney;
    std::cout << "nn Congratz, You now have a bank accout! nn";
    clearscreen();
    return 0;
     
    
}

Answer

Your pointer casting is all over the map and certainly “unusual” and incorrect for what you’re trying to do.

This line *i = createusern; is incorrect because i is not pointing to a string. It is pointing to a User object. That you really want to do here is something like this

User.setUsername( createusern );

…and the same goes for your other population attempts. You have setter functions for these elements, so use them.

You should also keep in mind that your User object is local and will not survive past the end of the createuser function