I am trying to write a program where you register a bank account and modify it. This is the code (Not full but just trying to experiment with file handling; I am a beginner at programming)
#include <iostream>
#include <fstream>
#include <string>
std::ofstream outfile;
std::ifstream infile;
std::fstream inout;
struct bank{
int acc_nr;
std::string emri;
std::string mbiemri;
};
std::istream& operator>> (std::ifstream& in, bank& klient)
{
in >> klient.emri;
in >> klient.mbiemri;
in >> klient.acc_nr;
return in;
}
std::ostream& operator<< (std::ofstream& out, bank& klient)
{
out << klient.emri << std::endl;;
out << klient.mbiemri << std::endl;
out << klient.acc_nr << std::endl;
return out;
}
std::ostream& operator<< (std::fstream& out, bank& klient)
{
out << klient.emri << std::endl;;
out << klient.mbiemri << std::endl;
out << klient.acc_nr<< std::endl;
return out;
}
std::istream& operator>> (std::fstream& in, bank& klient)
{
in >> klient.emri;
in >> klient.mbiemri;
in >> klient.acc_nr;
return in;
}
std::istream &read(bank &klient, std::istream &is)
{
std::cout << "Jepni emrin: ";
is >> klient.emri;
std::cout << "Jepni mbiemrin: ";
is >> klient.mbiemri;
std::cout << "Jep numrin e akaundit: ";
is >> klient.acc_nr;
return is;
}
const std::ostream &print(bank klient, std::ostream &os)
{
std::cout << "Emri: ";
os << klient.emri;
std::cout << "\nMbiemri: ";
os << klient.mbiemri;
std::cout << "\nNumri i akaundit: ";
os << klient.acc_nr;
return os;
}
void read_infile(bank &klient)
{
read(klient, std::cin);
outfile.open("C:\\publik\\sample.dat", std::ios::app| std::ios::binary);
outfile.write(reinterpret_cast <char *>(&klient), sizeof(bank));
outfile.close();
}
void print_outfile(bank klient)
{
infile.open("C:\\publik\\sample.dat", std::ios::in| std::ios::binary);
infile.read(reinterpret_cast <char *>(&klient), sizeof(bank));
infile.close();
}
void kerko(std::string emri, std::streampos& a)
{
bank temp;
inout.open("C:\\publik\\sample.dat", std::ios::in | std::ios::out | std::ios::binary);
while (inout.read(reinterpret_cast <char *>(&temp), sizeof(bank)))
{
if (emri == temp.emri) // emri = name.
{
print(temp, std::cout);
a = inout.tellg();
inout.close();
break;
}
}
}
int main()
{
bank klient;
bank temp2;
std::string emri;
std::streampos a;
std::cin >> emri;
bank temp;
kerko(emri,a);
std::cout <<std::endl;
system("pause");
return 0;
}
The code reads a name, searches through the file and then displays its information. The searching and displaying are successful but I get this error
Unhandled exception at 0x77CFDF58 (msvcp120d.dll) in Banke.exe: 0xC0000005: Access violation reading location 0x00DCAB9C.
The code does not execute past the print function call in the while loop.
Thank you for your time.