학생 관리인을 만들고 싶습니다. 학생의 이름과 나이를 입력하는 정보를 원한다면 파일로 저장합니다. 내 응용 프로그램에 저장할 수는 있지만 읽는 방법은 무엇입니까? 이것은 내 코드이며, 파일의 모든 정보 학생을 읽을 수 있지만 첫 번째 학생은 제외합니다. 왜 그런지 몰라?줄 단위로 문자열을 읽는 방법
#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();
}
'new []'대신'std :: vector'를 사용하십시오. 최소한의 말로 메모리 누수가 있습니다. 그리고 "C++ getline skipping"을 찾으십시오. 왜냐하면 그것이 여기서도 문제가되기 때문입니다. – chris
@chris : 왜 벡터입니까? 죄송합니다 C++을 처음 접해 보았습니다. 이해할 수 없습니다. –
솔직히 말해서 배우로 사용하는 책이나 리소스에 대해 동적 배열로 포인터 앞에 가르쳐야합니다. 'std :: vector'를 사용하는 방법에 대한 많은 예제가 있으며 왜 인생을 훨씬 더 좋게 만듭니다. – chris