0

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();
}
mthe.net
  • 119
  • 2
  • 10
  • 1
    Please use a `std::vector` instead of that `new[]`. You have a memory leak to say the least. And look up "C++ getline skipping" because that's a problem here as well. – chris Jul 12 '13 at 04:59
  • @chris: why is vector? Sorry I am new to C++, I don't understand that – mthe.net Jul 12 '13 at 07:51
  • To be honest, it should be taught before pointers as dynamic arrays in whatever book or resource you're using to learn. There are tons of examples out there on how to use `std::vector` and why it makes life so much better. – chris Jul 12 '13 at 07:59
  • @chris: I am not study at school, I just study at home – mthe.net Jul 12 '13 at 08:07
  • 1
    And a good [book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) would be an extremely helpful asset to do so. – chris Jul 12 '13 at 08:15

1 Answers1

0

Your input() function is fine. The problem is that you are calling the readfile() function -- which doesn't make sense since you've already loaded the input data once. Your readfile() does not call ignore(), which causing it to override the correct data that you previously had.

cheeyos
  • 671
  • 4
  • 11