ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 실습문제. 클래스를 이용하여 단어장 만들기.
    C++ 2022. 1. 17. 11:39

    문제. 아래의 WordPair구조체와 Mydic 클래스를 이용하여 영어와 한글이 한 쌍을 이루는 나만의 영어 단어장 프로그램을 구현하라.

    ex)

    apple 사과

    decide 결정하다

     

    	struct WordPair {
    		string eng;
    		string kor;
    	};
    class MyDic {
    
    WordPair words[100]; // 저장된 단어 배열
    	int nWords = 0; // 현재 등록된 단어의 수
    
    public :
    	void add(string eng, string kor); // 하나의 단어 추가
    
    	void load(string filename); // 파일에서 단어 읽기
    		
    	void save(string filename); // 파일에 모든 단어 저장
    		
    	void print(); // 모든 단어를 화면에 출력
    		
    	string getEng(int id); // id번째의 영어단어 반환
    
    	string getKor(int id) { // id번째의 한글 설명 반환
    };

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

    정답.

    #include <iostream>
    #include <fstream>
    using namespace std;
    
    #define MAXWORDS 100
    
    class MyDic {
    
    	struct WordPair {
    		string eng;
    		string kor;
    	};
    
    	WordPair words[MAXWORDS]; // 저장된 단어 배열
    	int nWords = 0; // 현재 등록된 단어의 수
    
    public :
    	void add(string eng, string kor) { // 하나의 단어 추가
    		words[nWords].eng = eng;
    		words[nWords].kor = kor;
    		nWords++;
    	}
    
    	void load(string filename) { // 파일에서 단어 읽기
    		ifstream f1(filename);
    		if (f1) {
    			f1 >> nWords;
    			for (int i = 0; i < nWords; i++) {
    				f1 >> words[i].eng >> words[i].kor;
    			}
    		}
    		f1.close();
    	}
    	void save(string filename) { // 파일에 모든 단어 저장
    		ofstream f1(filename);
    		if (f1) {
    			f1 << nWords << endl;
    
    			for (int i = 0; i < nWords; i++) {
    				f1 << words[i].eng << " " << words[i].kor << endl;
    			}
    		}
    		f1.close();
    	}
    	void print() { // 모든 단어를 화면에 출력
    		for (int i = 0; i < nWords; i++) {
    			cout << words[i].eng << " " << words[i].kor << endl;
    		}
    	}
    	string getEng(int id) { // id번째의 영어단어 반환
    		return words[id].eng;
    	}
    	string getKor(int id) { // id번째의 한글 설명 반환
    		return words[id].kor;
    	}
    };
    
    
    int main()
    {
    	MyDic word;
    	MyDic word2;
    	word.add("Coda", "천재");
    	word.add("decide", "결정하다");
    	word.save("words.txt");
    	word2.load("words.txt");
    	word2.print();
    
    	cout << word.getEng(0) << endl;
    	cout << word.getKor(1) << endl;	
    }
Designed by Tistory.