관리 메뉴

moozi

파일입출력예제 클래스버젼 본문

C++

파일입출력예제 클래스버젼

moozi 2015. 10. 30. 17:31

#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

/* 클래스 생성 */
class Student {
private: 
 char name[10], dept[20], sid[11], address[50];
public:
 void inputData() {
  /*  파일오픈 - 쓰기   */
  ofstream fout;
  fout.open("student.txt", ios::out | ios::app); // 추가(append)모드

  /* 데이터입력      */
  while (true) {
   cout << "이름 : ";
   cin.getline(name, 10); // 한줄 입력받아서 name에 저장
   if (strcmp(name, "exit") == 0) {
    break; // while문 종료
   }
   cout << "학과 : ";
   cin.getline(dept, 20);// 한줄 입력받아서 dept에 저장
   cout << "학번 : ";
   cin.getline(sid, 11); // 한줄 입력받아서 sid에 저장
   cout << "주소 : ";
   cin.getline(address, 50);


   if (!fout) {
    cout << "파일오픈 에러!";
    return;
   }

   /* 파일 쓰기   */
   fout << name << endl;
   fout << dept << endl;
   fout << sid << endl;
   fout << address << endl;


  }

  /* 파일 닫기 */
  fout.close();

 };

 void outputData() {
  /* 파일오픈 - 읽기 */
  ifstream fin("student.txt");
  if (!fin) {
   cout << "파일오픈에러" << endl;
   return;
  }

  /* 파일에서 한글자씩 eof일 때까지 읽기 */
  /* int c = 0;
   while ((c = fin.get()) != -1) {
   cout << (char)c;
  } */
  /* 파일에서 한줄씩 eof일 때까지 읽기 */
  char buf[100];
  while (true) {
   fin.getline(buf, 100);
   if (fin.eof()) {
    break;
   }
   cout << buf << endl;
  }

  /* 파일 닫기 */
  fin.close();

 };

 void search() {
  vector<string> wordVector;
  /* 파일오픈 - 읽기 */
  ifstream fin("student.txt");
  if (!fin) {
   cout << "파일오픈에러" << endl;
   return;
  }
  string line;
  while (true) {
   getline(fin, line);
   if (fin.eof()) {
    break;
   }
   wordVector.push_back(line);//한줄 읽어서 벡터에 추가
  }
  /* 파일 닫기 */
  fin.close();

  while (true) {
   cout << "검색할 단어를 입력하세요 >>";
   string word;
   getline(cin,word);
   if (word == "exit") {
    break;
   }
   /* 단어검색 */
   for (int i = 0;i < wordVector.size();i++) {
    int index = wordVector[i].find(word);
    if (index != -1) {
     cout << wordVector[i] << endl;//검색된 단어 출력
    }
   }
  }
 }

 

};

int main() {
 //인스턴스생성
 Student hongildong;
 hongildong.inputData(); //데이터입력
 hongildong.outputData(); //데이터출력
 hongildong.search();//검색

 return 0;
}

'C++' 카테고리의 다른 글

끝말잇기게임 클래스 버전  (0) 2015.11.17
끝말잇기게임  (0) 2015.11.12
파일입출력 클래스 버전 -주소록  (1) 2015.11.03
파일입출력 예제  (0) 2015.10.27
Comments