c++ - 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!";
}
}
解决方案
正如在评论中提到的那样,您不应该像存储在 RAM 中那样编写对象,特别是如果它们具有一些“类似引用”的语义,例如您的帐户 std::string 的子对象。
在这种情况下你写的通常是一个指针和一个长度。问题是,当您再次读取数据时,加载的指针指向“垃圾”。
推荐阅读
- python - 在 Django 网站中提交表单后,如何执行繁重的后台 python 代码?
- image - 无法从本地路径加载Nativescript vue中的图片,但是用http/https就可以了,为什么?
- apache-spark - 未经授权的错误将批处理大表设置为 Spark 流中的数据主机
- automation - 将表单自动化到 2 个单独的网站
- timer - 状态和计时器的问题 - apache beam
- python-3.x - 为什么python的文档生成器--sphinx搜索栏中没有cjk(chinese)词的搜索结果?
- sql-server - 如何从 SSIS 中的 DateTime 变量小时、分钟、秒和其他部分中删除
- vb.net - 将记录插入访问数据库的随机失败
- conemu - 闪烁关闭 - 光标仍在闪烁 - ConEmu 和 Cmder
- powershell - .Replace 适用于 powershell 但不适用于批处理脚本