Sorry fot the delay
The full code is too long because I use yes_no functions, other functions to modify and display the variables. Also instead of system("pause") I use a function I had seen in a Duoas post, but I use system() now because it's shorter. However I'll post the most important parts
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
#include <iostream>
#include <string>
#include <fstream>
#include <windows.h>
class Employee
{
public:
string m_Name;
string m_Gender;
string m_Address;
int m_id;
int m_Age;
int m_Phone;
int m_Salary;
int m_Department;
}
|
I create a new object
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
int main()
{
Employee employee1;
create_new_employee(employee1);
string filename = "employee_test.txt";
ofstream outfile;
outfile.open (filename.c_str(), ios::out|ios::binary|ios::app);
outfile.write ( (char *)(&employee1), sizeof(Employee) );
outfile.close();
system("pause");
return 0;
}
|
When void create_new_employee(Employee& employee1) is called, it basically assigns values using the following two functions.
1 2 3 4 5 6 7 8 9
|
string give_info_t( string question )
{
string info;
cout << question << ": ";
getline (cin,info);
return info;
}
|
if the answer is text (name, address...), or
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
|
int give_info_n(string question)
{
int info, bad_input;
do{
bad_input=0;
cout << question << ": ";
cin >> info;
cin.ignore();
if(!cin)
{
bad_input=1;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "\nYou made an illegal choice.\n\n";
}
}while(bad_input);
return info;
}
|
if the answer is number (Age, salary)
Example : employee1.m_Name = give_info_t( "Name" );
employee1.m_Age = give_info_n( "Age" );
To read the variables (using different program):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
int main()
{
Employee employee2;
string filename = "employee_test.txt";
ifstream infile;
infile.open (filename.c_str(), ios::in|ios::binary);
while( infile.read ( (char *)&employee2, sizeof(Employee) ) )
infile.close();
cout << employee2.m_Name << endl;
...
system("pause");
return 0;
}
|
I changed the code a bit from my first post, but the problem remains. The values are assigned OK, and I can see that because a display them before I save them in the file, but when I read from the file the first three lines that contain strings are displayed empty and after them all the other numbers are OK.