I’m trying to do a basic project that was bank management system. I need to store and access the information from binary file using file handling. I had successfully write the information by class objects into the file. But, the code is getting crashed when i was reading from the file by class objects.
The code i’ve been working is given below
void Bank::addAccount()
{
Account newAccount;
newAccount.createAccount();
std::ofstream account_data(file_path, std::ios::out | std::ios::binary | std::ios::app);
if (!account_data)
{
cout << "Error! Can't able to open the file" << endl;
return;
}
std::cout << newAccount.getAccountNo() << std::endl;
std::cout << newAccount.getId() << std::endl;
std::cout << newAccount.getName() << std::endl;
std::cout << newAccount.getAddress() << std::endl;
std::cout << newAccount.getContact() << std::endl;
std::cout << newAccount.getBalance() << std::endl;
account_data.write(reinterpret_cast<char*>(&account_data), sizeof(account_data));
account_data.close();
void Bank::showAccount()
{
string acc_no;
cout << "Enter the account no: ";
cin >> acc_no;
std::ifstream file(file_path, std::ifstream::binary);
if (!file)
{
std::cout << "Error! Can't able to open the file" << std::endl;
return;
}
Account acc;
while (file.read(reinterpret_cast<char*>(&acc), sizeof(acc)))
{
if (acc.getAccountNo() == acc_no)
{
std::cout << acc.getAccountNo() << std::endl;
std::cout << acc.getId() << std::endl;
std::cout << acc.getName() << std::endl;
std::cout << acc.getAddress() << std::endl;
std::cout << acc.getContact() << std::endl;
std::cout << acc.getBalance() << std::endl;
}
}
file.close();
}
class Account source file
string Account::getAccountNo() const
{
return m_account_no;
}
string Account::getId() const
{
return m_customer_id;
}
string Account::getName() const
{
return m_name;
}
string Account::getAddress() const
{
return m_address;
}
string Account::getContact() const
{
return m_contact_no;
}
float Account::getBalance() const
{
return m_balance;
}
void Account::createAccount()
{
cout << "nEnter the Account no: ";
cin >> m_account_no;
//m_customer_data.setCustomerData();
cout << "nEnter the customer ID: ";
cin >> m_customer_id;
cin.ignore();
cout << "nEnter the name: ";
getline(cin, m_name);
cout << "nEnter the address: ";
getline(cin, m_address);
cout << "nEnter the contact_no: ";
cin >> m_contact_no;
cout << "nEnter the initial deposit amount: ";
cin >> m_balance;
cout << "n-------------------------------------------------------------------nn";
}
New contributor
Muthuraj is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.