I want to make an application student manager. I want to user input information of a student just name and age, and then application will save it in a file. I can for my application save it, but how to read it? This is my code, It can read all information student in file but except first student. I don't know why?
#include<iostream>
#include<iomanip>
#include<fstream>
using namespace std;
struct St
{
string name;
int age;
};
class StManager
{
int n;
St *st;
public:
StManager()
{
n = 0;
st = NULL;
}
void input();
void output();
void readfile();
void writefile();
};
void StManager::input()
{
cout << "How many students you want to input?: ";
cin >> n;
st = new St[n];
for(int i=0; i<n; i++) {
cout << "Input student #"<<i<<":"<<endl;
cout << "Input name: ";
cin.ignore();
getline(cin, st[i].name);
cout << "Input age: "; cin>>st[i].age;
cout <<endl;
}
}
void StManager::writefile()
{
ofstream f;
f.open("data", ios::out|ios::binary);
f<<n;
f<<endl;
for(int i=0; i<n; i++)
f<<st[i].name<<setw(5)<<st[i].age<<endl;
f.close();
}
void StManager::readfile()
{
ifstream f;
f.open("data", ios::in|ios::binary);
f >> n;
for(int i=0; i<n; i++) {
getline(f, st[i].name);
f>>st[i].age;
}
f.close();
}
void StManager::output()
{
for(int i=0; i<n; i++) {
cout << endl << "student #"<<i<<endl;
cout << "Name: " << st[i].name;
cout << "\nAge: " << st[i].age;
}
}
int main()
{
StManager st;
st.input();
st.writefile();
cout << "\nLoad file..."<<endl;
st.readfile();
st.output();
}