Below program take three details of family members i.e name,age and occupation. Stores them in txt file.
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <fstream>
using namespace std;
class Dewan_Family
{
char name[50]; // array for name of the family member
int age; // integer for age of the family member
char oc[50]; // array for occupation of family member
public:
void getdata(); // This func. to collect information
void displaydata(); // This func to display information
};
void Dewan_Family::getdata() // creating func. to get family members info
{
cout << "Enter the Name of the Family member: "; cin.getline(name,50);
cout << "Enter the Age of the member: ";
cin >> age;
cin.ignore();
cout << "Enter the occupation of the member: "; cin.getline(oc,50);
}
void Dewan_Family::displaydata() // creating func. to display info
{
cout << "Name of the Dewan family's member: " << name << endl;
cout << "Age of the member: " << age << endl;
cout << "Occupation of the member: " << oc << endl;
}
int main()
{
Dewan_Family obj[5]; // created object array of class Dewan_Family
fstream file; // created object to handle file
file.open("family.txt", ios_base::app | ios_base::in); // created and attached file with the object.
char ch;
int choice; int j=0;
cout << "Main Menu ! Choose any option 1-3.\n";
cout << "1. To add Members\n";
cout << "2. To Display all Members\n";
cout << "3. Exit\nChoice: ";
cin >> choice;
cin.ignore();
cout << "\n";
switch(choice)
{
case 1: ch='y';
do{
obj[j].getdata();
file.write((char*)&obj[j],sizeof(obj[j]));
j++;
cout << "Data added successfully !.\nDo you want to continue to add: y or n: ";
cin >> ch;
}while(ch =='y' || ch == 'Y');
break;
case 2: file.seekg(0);
while(file)
{
file.read((char*)&obj[j],sizeof(obj[j]));
obj[j].displaydata();
j++;
}
break;
case 3: exit(1);
};
return 0;
}
My question is as follow:- 1) This little program successfully write data(with write function) to family.txt file. But when I see data by opening this family.txt file, data appears in weird form.
for example if I enter below details
Name = Ashok Dewan
Age = 25
occupation = job
then data in the text file is like this
Ashok #{}@1.^.36 .. ) job#..#...
2) when I read data(with read func.) It display like below
Name of the Dewan family's member: Ashok Dewan
Age of the member: 25
Occupation of the member: Job
Name of the Dewan family's member: ##$8&
Age of the member: 42565571
Occupation of the member: {...&6^
It displays other data also which I did not enter. I don't know Why it is showing extra data. Is this because write() and Read() use binary mode also by default? Please check this code at your end. I am using latest codeblocks Please help me to understand this behaviour?