I use VC++ 6.0
1) This small program simply reads infomation from file “in.txt” and write it in file “out.txt”. (copy contents from this file to another)
2) It doesn’t work. The compiler issues an execution-time error. And the ouput text file “out.txt” is empty.
3) I don’t know why it issues an error. Please help me fix it using member function “read”. Thank you handsome guys ^^.
4) My input text file “in.txt” has form:
1 Bob 100
2 Lina 300
3 John -99
#include <iostream>
using std::cout;
using std::cin;
using std::endl;
using std::ios;
using std::ostream;
#include <fstream>
using std::ifstream;
using std::ofstream;
#include <string>
using std::string;
class ClientData
{
public:
ClientData(int acc = 0, string n = "", double bal = 0);
~ClientData(){};
void setClientData(int acc, string n, double bal);
void setAccount(int acc);
void setName(string n);
void setBalance(double bal);
int getAccount() const { return account; }
double getBalance() const { return balance; }
string getName() const { return name; }
private:
int account;
string name;
double balance;
};
ClientData::ClientData(int acc, string n, double bal)
{
setClientData(acc, n, bal);
}
void ClientData::setClientData(int acc, string n, double bal)
{
setAccount(acc);
setName(n);
setBalance(bal);
}
void ClientData::setAccount(int acc)
{
account = acc;
}
void ClientData::setName(string n)
{
name = n.length == 0 ? "No name" : n;
}
void ClientData::setBalance(double bal)
{
balance = bal;
}
void outputLine(ostream &output, const ClientData &record);
void main()
{
ifstream in("in.txt");
ofstream out("out.txt");
ClientData client;
// THIS BLOCK CAUSES ERROR //
while(in.read(reinterpret_cast<char *>(&client), sizeof(ClientData)))
{
outputLine(out, client);
}
}
void outputLine(ostream &output, const ClientData &record)
{
output << record.getAccount() << " ";
output << record.getName() << " ";
output << record.getBalance() << " ";
output << endl;
}