Binary File to read Student name and number
Jan 18, 2016 at 2:24am UTC
Hi everybody!
So basically I'm trying to enter some names and numbers of some students and append their data using a while loop. I am able to get the program to append their data without any problem:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
#include <iostream>
#include <fstream>
using namespace std;
const int MAX=100;
struct Student
{
char firstname[MAX];
//char lastname[MAX];
int number;
char module;
};
int main()
{
fstream fileB;
int loop=1;
char choice;
Student data;
cout<<"Append some records\n" ;
fileB.open("infile.dat" ,ios::out | ios::app | ios::binary);
if (!fileB)
{
cout<<"CANNOT OPEN FILE\n" ;
exit(-1);
}
while (loop)
{
cout<<"Enter student name: " ;
cin>>data.firstname;
cout<<"Enter student data: " ;
cin>>data.number;
fileB.write ((char *) &data, sizeof (Student));
//fileB.seekp (0,ios::end);
cout<<"Continue? " ;
cin>>choice;
switch (choice)
{
case 'Y' :
case 'y' : loop = 1;
break ;
case 'N' :
case 'n' : loop = 0;
break ;
default : cout << "Please choose the right option!" << endl;
}
}
fileB.close();
}
The code for creating the binary file is in a separate code, which works without error as well.
Which is not a problem. However, when I want the program to read the binary file, using this code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
#include <iostream>
#include <fstream>
using namespace std;
const int MAX=25;
struct Student
{
char name[MAX];
int number;
char module;
};
int main()
{
ifstream fileB;
int loop=1;
char choice;
Student data;
fileB.open("infile.dat" ,ios::in|ios::binary);
while (fileB.read((char *)(&data),sizeof (Student)))
{
//fileB.seekp (0,ios::end);
cout<<data.number<<" " <<data.name<<endl;
}
fileB.close();
}
it came out like this:
1 2 3 4 5 6 7
0 StudentA
4788208 -random line-
237263 **garbage variables**
0 StudentB
4788208
251625 **garbage variables**
when it's supposed to be:
1 2
237263 StudentA
251625 StudentB
Did I miss out anything in one of the two codes?
Last edited on Jan 18, 2016 at 2:27am UTC
Jan 18, 2016 at 2:36am UTC
first code:
const int MAX=100 ;
second code:
const int MAX=25 ;
Topic archived. No new replies allowed.