class book { private: char name[10]; char title[100]; int page; public: book() { int i; for(i = 0; i < 10; i++)name[i] = 0; for(i = 0; i < 100; i++)title[i] = 0; page = 0; } int check() { if(page == 0)return 0; else return -1; } void insert() { if(page == 0) { cout << "책 제목을 입력해 주세요 : "; cin >> title; cout << "저자를 입력해 주세요 : "; cin >> name; cout << "page를 입력해 주세요 : "; cin >> page; } else cout << "이미 저장된 책이 있습니다." << endl; } void del() { if(page != 0) { int i; for(i = 0; i < 10; i++)name[i] = 0; for(i = 0; i < 100; i++)title[i] = 0; page = 0; } else cout << "저장된 책이 없습니다." << endl; } void modify() { if(page != 0) { cout << "책 제목을 입력해 주세요 : "; cin >> title; cout << "저자를 입력해 주세요 : "; cin >> name; cout << "page를 입력해 주세요 : "; cin >> page; } else cout << "저장된 책이 없습니다." << endl; } void print() { if(page != 0) { cout << "책 제목 : " << title << endl; cout << "저 자 : " << name << endl; cout << "page : " << page << endl; } } }; void main() { book bk[10]; int cmd; int index = 0; while(1) { cout << "입력[0] 삭제[1] 수정[2] 출력[3] 종료[-1] : "; cin >> cmd; if(cmd == 0) { int insert_index; for(insert_index = 0; insert_index < index; insert_index++) { if(bk[insert_index].check() == 0) { bk[insert_index].insert(); break; } } if(insert_index == index)bk[index++].insert(); } else if(cmd == 1) { int del_index; cout << "삭제할 책의 index를 입력해 주세요 : "; cin >> del_index; bk[del_index].del(); } else if(cmd == 2) { int modi_index; cout << "수정할 책의 index를 입력해 주세요 : "; cin >> modi_index; bk[modi_index].modify(); } else if(cmd == 3) { int i; for(i = 0; i < index; i++)bk[i].print(); } else if(cmd == -1) { break; } } }
프로그램 실행화면
C++로 구현한 도서관리 프로그램이다. 그리 복잡한 기능이 들어간 것이 아니라 단순히 책의 제목, 저자, 페이지 수를 저장할 수 있는 프로그램이다. 최대 10권까지 저장할 수 있다.
클래스를 연습하는데 좋은 예제인 것 같다. 프로그램 설명은 굳이 필요하진 않을 것 같고 main함수의 cmd의 값에 따라 어떻게 처리되는지 프로그램을 보면 쉽게 이해될 것 같다.
배열을 사용할 때 차곡 차곡 쌓다가 중간쯤에 저장된 것을 삭제하면 중간 부분이 비게 된다. 이를 무시하고 저장을 한다면 10권을 저장할 수 있는 것이 아니라 결국엔 한권도 저장할 수 없는 프로그램이 된다.
그래서 del_index를 통해서 이를 해결했다. 빈 곳이 있다면 그곳부터 저장을 하는 것이다.