0

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

Biffen
  • 6,249
  • 6
  • 28
  • 36
  • 4
    `file.write((char*)&obj,sizeof(obj));` is writing the value of the pointer `obj` to the file. It will be useless. Writing byte data of the struct `User` will also be useless because it contains `string`, which should contain pointers. You should define the file format to store the strings and write encoder (convert `User` to file data (bytes)) and decoder (convert file data back to `User`) according to that. – MikeCAT Jun 22 '21 at 13:35
  • 3
    Anyway, `cin>>n; User u[n];` defines a Variable Length Array which is explicitely **not** defined by any version of the C++ standard. You'd better use a vector here. – Serge Ballesta Jun 22 '21 at 13:37

0 Answers0