jeudi 26 février 2015

IO Binary Writing Using Seekp; Moving Down Lines


This program is supposed to create a binary file called Record.bin, and then write all of the information that the user inputs into that file. Right now it gets to the part where it reads in Student B[10], and it reads B[0] correctly, but all of the following elements of B[] are one step off. I can't figure out how to include a delimiter when the value is an integer.


After that there are some issues with my seeking, but I can't seem to understand why.



#include <iostream>
#include <cstring>
#include <sstream>
#include <istream>
#include <fstream>
using namespace std;
struct Student
{
char Name[20];
char ANumber[9];
int Age;
float GPA;
};
int main(){
Student A[10];
Student B[10];
for (int i = 0; i < 10; i++){
cout << "Enter student's name" << endl;
cin >> A[i].Name;
cout << "Enter ANumber" << endl;
cin >> A[i].ANumber;
cout << "Enter Age" << endl;
cin >> A[i].Age;
cout << "Enter GPA" << endl;
cin >> A[i].GPA;
}
fstream fout("Record.bin", ios::out | ios::binary);
for (int i = 0; i < 10; i++){
fout << A[i].Name << endl;
fout << A[i].ANumber << endl;
fout << A[i].Age << endl;
fout << A[i].GPA << endl;
}
fout.close();
fstream fin("Record.bin", ios::in);
char input[25];
for (int i = 0; i < 10; i++){
fin.getline(B[i].Name, 25, '\n');
fin.getline(B[i].ANumber, 25, '\n');
fin >> B[i].Age;
fin >> B[i].GPA;
}
fin.close();

fin.open("Record.bin", ios::in);
Student C;
string temp2;
fin.seekp(4 * sizeof(Student), ios::beg);
fin.getline(C.Name, 25, '\n');
fin.getline(C.ANumber, 25, '\n');
fin >> C.Age;
fin >> C.GPA;

fin.close();

fin.open("Record.bin", ios::in | ios::out | ios::binary);
fin.seekp(4 * sizeof(Student), ios::end);
fin.write(C.Name, sizeof(C.Name));
fin.write(C.ANumber, sizeof(C.ANumber));
fin << C.Age;
fin << C.GPA;
fin.close();

}



Aucun commentaire:

Enregistrer un commentaire