2013-07-12 5 views
0

학생 관리인을 만들고 싶습니다. 학생의 이름과 나이를 입력하는 정보를 원한다면 파일로 저장합니다. 내 응용 프로그램에 저장할 수는 있지만 읽는 방법은 무엇입니까? 이것은 내 코드이며, 파일의 모든 정보 학생을 읽을 수 있지만 첫 번째 학생은 제외합니다. 왜 그런지 몰라?줄 단위로 문자열을 읽는 방법

#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(); 
} 
+1

'new []'대신'std :: vector'를 사용하십시오. 최소한의 말로 메모리 누수가 있습니다. 그리고 "C++ getline skipping"을 찾으십시오. 왜냐하면 그것이 여기서도 문제가되기 때문입니다. – chris

+0

@chris : 왜 벡터입니까? 죄송합니다 C++을 처음 접해 보았습니다. 이해할 수 없습니다. –

+0

솔직히 말해서 배우로 사용하는 책이나 리소스에 대해 동적 배열로 포인터 앞에 가르쳐야합니다. 'std :: vector'를 사용하는 방법에 대한 많은 예제가 있으며 왜 인생을 훨씬 더 좋게 만듭니다. – chris

답변

0

귀하의 input() 기능은 괜찮습니다. 문제는 readfile() 함수를 호출하는 것입니다. 입력 데이터를 한 번로드 했으므로 이해가되지 않습니다. readfile()ignore()을 호출하지 않으므로 이전에 가지고 있던 올바른 데이터가 무시됩니다.

+0

네, 정말 고마워요.) –

관련 문제