I am trying to write a text file from an object array. But its not successful. I am using .write() method to write the object details into a text file
main.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include <list>
#include <iterator>
#include <sstream>
#include "UserBO.cpp"
using namespace std;
int main() {
int n, i;
ofstream f;
f.open("example.txt");
string name, contactnumber, username, password;
cout << "Enter the number of users:" << endl;
cin >> n;
User u[n];
for (i = 0; i < n; i++) {
cout << "Enter the name of user:" << endl;
cin >> name;
cout << "Enter the contact number:" << endl;
cin >> contactnumber;
cout << "Enter the username:" << endl;
cin >> username;
cout << "Enter the password:" << endl;
cin >> password;
u[i] = User(name, username, password, contactnumber);
}
UserBO p;
p.writeUserdetails(f, u, n);
return 0;
}
User.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include <list>
#include <iterator>
#include <sstream>
using namespace std;
class User {
string name;
string username;
string password;
string contactnumber;
public:
User() {}
User(string name, string username, string password, string contactnumber) {
this->name = name;
this->username = username;
this->password = password;
this->contactnumber = contactnumber;
}
string getName() { return name; }
string getUsername() { return username; }
string getPassword() { return password; }
string getContactnumber() { return contactnumber; }
};
UserBO.cpp
#include <iostream>
#include <string>
#include <stdio.h>
#include <fstream>
#include <list>
#include <iterator>
#include <sstream>
#include "User.cpp"
using namespace std;
class UserBO {
public:
void writeUserdetails(ofstream &file, User obj[], int m) {
file.write((char *)&obj, sizeof(obj));
}
};
Output of the file example.txt
ûq
Kindly try to find the error in my code. I have used .write() method to write a object array into exmaple.txt