首页 > 解决方案 > C++ 二进制输入/输出文件读/写访问破坏

问题描述

我试图从文件中读取传递字符串,然后比较它是否传递正确但发生读/写访问冲突。如果我将其与帐号 int 进行比较,则工作正常,但 hwen 与 srig 进行比较,则出现此错误,另一件事是,即使我尝试使用 int acount 读取该实例,我也无法使用存储在二进制文件中的该帐户实例数字。但是当我创建新的 instatiate 并将其存储在文件中时,新的 insatitae 可用于与 int 进行比较,直到它不与字符串进行比较

here is my class**
    
class account {
    std::string name , pass;
    int acno , balance;
    public:
        int getAcno()
        {
            return acno;
        }
        std::string getPass()
        {
            return pass;
        }
            std::string getName()
            {
                return name;
            }
            int getBalance()
            {
                return balance;
            }
            void createAccount()
            {
                std::cout << "\n\tEnter the account number : ";
                std::cin >> acno;
                std::cin.ignore(32767, '\n');
                std::cout << "\n\tEnter the account pass : ";
                std::cin >> pass;
                std::cin.ignore(32767, '\n');
                std::cout << "\n\tEnter the name of account holder : ";
                std::getline(std::cin , name);
                std::cin.ignore(32767, '\n');
                std::cout << "\n\tEnter the current balance : ";
                std::cin >> balance;
                std::cin.ignore(32767, '\n');
                
            }
            void showAccount()
            {
                std::cout << "\n\n\tAccount number : " << acno;
                std::cout << "\n\tAccount holder name : " << name;
                std::cout << "\n\tBalance : " << balance;
            }
    
    };
    '''
        here is my access function 
        void login()
        {
            std::ifstream infile{ "user.dat" , std::ios::binary | std::ios::in};
            if (!infile)
            {
                std::cout << "\n\tError! cannot open the file";
                return;
            }
        
            int acno;
            std::string pass = "jam";
            std::cout << "\n\n\tEnter the account number: ";
            std::cin >> acno;
            std::cout << "pass";
            std::cin >> pass;
            account new_account;
            bool flag = false;
            while (infile.read((char*)&new_account, sizeof(new_account)))
            {
                if (new_account.getPass() == pass)
                {
                    new_account.showAccount();
                    flag = true;
                    break;
                }
            }
            if (flag == false)
            {
                std::cout << "\n\tSorry! Account number not found!";
                    }
                }

标签: c++c++17

解决方案


正如在评论中提到的那样,您不应该像存储在 RAM 中那样编写对象,特别是如果它们具有一些“类似引用”的语义,例如您的帐户 std::string 的子对象。

在这种情况下你写的通常是一个指针和一个长度。问题是,当您再次读取数据时,加载的指针指向“垃圾”。


推荐阅读