안녕하세요 엘체프 입니다.

STL컨테이너의 요소로 변환 하여 교환해보는 실습으로 C++마무리 합니다.



문) 아래와 같이 비속어들과 그에 따른 교정어(바른 말)로 된 배열을 작성하고 이것을 STL 컨테이너의 요소로 변환하여

비속어 교정 사전을 만든 후, 특정 욕설 문장을 입력하였을 때 바로 교정하여 화면에 인쇄하는 프로그램입니다.


관련 예제 : 교과서 p.522 예제

 

   비속어 배열 요소들 : {"미친",     "뼉다귀",   "염병",  "것들",   "빡쳐", "졸라"};
   교정어 배열 요소들 : {"정신나간", "고집쟁이", "이런", "사람들", "화나", "정말"};


출력 예시)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <string>
#include <map>
 
using namespace std;
 
int main(void) {
 
     string trashArr[]   = {"미친",     "뼉다귀",   "염병",  "것들",  "빡쳐", "졸라"};
     string correctArr[] = {"정신나간", "고집쟁이", "이런", "사람들", "화나", "정말"};
 
     int sizeArr = sizeof(trashArr) / sizeof(string);
     map<string, string> slangDic;
 
     for (int i=0; i<sizeArr; i++) {
        slangDic.insert(make_pair(trashArr[i], correctArr[i]));
     } // for
 
     /*map<string, string>::reverse_iterator it
        = slangDic.rbegin();
 
     while (it != slangDic.rend()) {
      cout << it->first << ", " << it->second << endl;
      it++;
     } // while*/
 
     string slangSent = "이 미친 염병 뼉다귀 같은 것들 때문에 졸라 빡쳐!";
     string correctSent;
 
     // 비속어 문장(slangSent) 비속어 사전 -> 검색
     // 교정어 치환 -> 결과(correctSent) -> 인쇄
     // p.522/533
 
      map<string, string>::iterator it = slangDic.begin();
 
      size_t found;
 
      correctSent = slangSent; // 교정 문장 완성
 
       while (it != slangDic.end()) {
 
           found = correctSent.find((*it).first);
           
          while(found !=string::npos) {
 
            // 작성 시작 
          // 작성 힌트)
          // correctSent 문장 변수에서 found 변수(검색 단어 변수)
          // 를 it 반복자 패턴 변수의 값(second)로 교체(replace)하는
          // 한개의 문장을 작성합니다. p.523 중단의 replace 구문 참조
   
            

            // 작성 끝
            found = correctSent.find((*it).first, 
                                    found+1);
          } // while
 
          it++;
 
         } // while // 치환 완료
 
 
     cout << slangSent << endl;  // 교정전 문장
     cout << correctSent << endl; // 교정 후 문장
 
     system("PAUSE");
     return 0;
}


----------------------------------------------

답안소스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <iostream>
#include <string>
#include <map>
 
using namespace std;
 
int main(void) {
 
     string trashArr[]   = {"미친",     "뼉다귀",   "염병",  "것들",  "빡쳐", "졸라"};
     string correctArr[] = {"정신나간", "고집쟁이", "이런", "사람들", "화나", "정말"};
 
     int sizeArr = sizeof(trashArr) / sizeof(string);
     map<string, string> slangDic;
 
     for (int i=0; i<sizeArr; i++) {
        slangDic.insert(make_pair(trashArr[i], correctArr[i]));
     } // for
 
     /*map<string, string>::reverse_iterator it
        = slangDic.rbegin();
 
     while (it != slangDic.rend()) {
      cout << it->first << ", " << it->second << endl;
      it++;
     } // while*/
 
     string slangSent = "이 미친 염병 뼉다귀 같은 것들 때문에 졸라 빡쳐!";
     string correctSent;
 
     // 비속어 문장(slangSent) 비속어 사전 -> 검색
     // 교정어 치환 -> 결과(correctSent) -> 인쇄
     // p.522/533
 
      map<string, string>::iterator it = slangDic.begin();
 
      size_t found;
 
      correctSent = slangSent; // 교정 문장 완성
 
       while (it != slangDic.end()) {
 
           found = correctSent.find((*it).first);
           
          while(found !=string::npos) {
 
            // 작성 시작 
            // 작성 힌트)
            // correctSent 문장 변수에서 found 변수(검색 단어 변수)
            // 를 it 반복자 패턴 변수의 값(second)로 교체(replace)하는
            // 한개의 문장을 작성합니다. p.523 중단의 replace 구문 참조
   
            correctSent.replace(found, 
                             (*it).first.length(), 
                             (*it).second);
            // 작성 끝
            found = correctSent.find((*it).first, 
                                    found+1);
          } // while
 
          it++;
 
         } // while // 치환 완료
 
 
     cout << slangSent << endl;  // 교정전 문장
     cout << correctSent << endl; // 교정 후 문장
 
     system("PAUSE");
     return 0;
}


'스터디 > C,C++' 카테고리의 다른 글

map 정렬 문제  (6) 2018.03.05
C++ map을 이용한 login 문제  (6) 2018.02.28
C 문자열(string) 분리  (6) 2018.02.28
C 문자열(string) 바꾸기  (6) 2018.02.28
마지막 C 시험문제 공백 사각찍기  (7) 2018.02.28

안녕하세요 엘체프 임돠

오늘은 map으로 정렬하는 문제로 map을 이해 해보도록 하겠습니다.


참고 링크) multimap 과 map의 차이점

http://blog.daum.net/coolprogramming/83


문) 영화 목록을 아래와 같이 오름차순 정렬하여 출력할 수 있도록 프로그램을 작성합니다.


실행화면 



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <iostream>
#include <map>
#include <string>
#include <list>
using namespace std;
typedef multimap<int, string>::iterator year_movie_it;
 
int findMovieYear(map<string, int> sortedMap, string movie) {
 
 int year;
 map<string, int>::iterator sit = sortedMap.find(movie);
 
 if (sit !=  sortedMap.end())
  year = sit->second;
 
 return year;
}
 
int main()
{
 multimap<int, string> year_movie_map;
 pair<int, string> year_movie[] = {
  make_pair(1998, "타이타닉"),
  make_pair(2008, "슬럼독 밀리어네어"),
  make_pair(1997, "인생은 아름다워"),
  make_pair(2003, "올드보이"),
  make_pair(1994, "라이온킹"),
  make_pair(1999, "매트릭스"),
  make_pair(1994, "포레스트검프"),
 };
  
 for (int i=0 ; i<sizeof(year_movie)/sizeof(pair<int, string>) ; i++)
 {
  year_movie_map.insert(year_movie[i]);
 }
 
 // 문1) 정렬할 수 있도록 movieList 라는 list 클래스의 객체변수를 만듭니다.  
 // hint) list의 구성요소는 문자열 성분이다.
 

 // 문2) 21번 라인에서 구성된 multimap에 반복자 패턴(iterator)를 결합하여 
 // it 라는 반복자 패턴 변수를 작성한다.

 
 // 문3) 정렬한 결과를 담을 수 있는 sortedMap이라는
 // map 객체 변수를 만들어서 기존의 multimap의 내용을 key와 value를
 // 반대로 뒤집어서 저장하여 정렬하도록 합니다. (참고로 아래는 문3) 세분화한 힌트입니다)
 
 // 과정-1) sortedMap map 객체 생성
 
 // 과정-2) while문을 사용하여 문제 2에서 만든 it 반복자 패턴객체
    를 이용하여 it의 키(it->first 또는 (*it).first)를 sortedMap
    의 으로 반대로 it의 값(it->second)은 sortedMap의 로 대입

 // 과정-3) 아래의 while문을 돌리기 위한 list<string>과 반복자 패턴
    (iterator)가 결합된 mit 라는 변수를 생성.  
 
 while (mit != movieList.end()) {
   sortedMap.insert(make_pair(*mit, findMovieYear(sortedMap, *mit)));
  mit++;
 } // while
 
 // 문4) 정렬된 sortedMap으로 주어진 결과와 같은 화면이
 // 인쇄될 수 있도록 코드를 작성하십시오.
 
 
 
 system("PAUSE");
 return 0;

}

--------------------------------------------
답안소스

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <iostream>
#include <map>
#include <string>
#include <list>
 
using namespace std;
 
typedef multimap<int, string>::iterator year_movie_it;
 
int findMovieYear(map<string, int> sortedMap, string movie) {
 int year;
 
 map<string, int>::iterator sit = sortedMap.find(movie);
 
 if (sit !=  sortedMap.end())
  year = sit->second;
 
 return year;
}
 
int main()
{
 multimap<int, string> year_movie_map;
 pair<int, string> year_movie[] = {
  make_pair(1998, "타이타닉"),
  make_pair(2008, "슬럼독 밀리어네어"),
  make_pair(1997, "인생은 아름다워"),
  make_pair(2003, "올드보이"),
  make_pair(1994, "라이온킹"),
  make_pair(1999, "매트릭스"),
  make_pair(1994, "포레스트검프"),
 };
  
 for (int i=0 ; i<sizeof(year_movie)/sizeof(pair<int, string>) ; i++)
 {
  year_movie_map.insert(year_movie[i]);
 }
 
 // 문1) 정렬할 수 있도록 movieList 라는 list 클래스의 객체변수를 만듭니다.  
 // hint) list의 구성요소는 문자열 성분이다.
 
    list<string> movieList;
 
  // 문2) 21번 라인에서 구성된 multimap에 반복자 패턴(iterator)를 결합하여 
  // it 라는 반복자 패턴 변수를 작성한다.    
 
    multimap<int, string>::iterator it = year_movie_map.begin();
 
 // 문3) 정렬한 결과를 담을 수 있는 sortedMap이라는
 // map 객체 변수를 만들어서 기존의 multimap의 내용을 key와 value를
 // 반대로 뒤집어서 저장하여 정렬하도록 합니다.
 
 map<string, int> sortedMap;
 
 while (it != year_movie_map.end()) {
 
  sortedMap.insert(make_pair(it->second, it->first));
  it++;
 } // while
 
 list<string>::iterator mit =  movieList.begin();
 
 while (mit != movieList.end()) {
 
  sortedMap.insert(make_pair(*mit, findMovieYear(sortedMap, *mit)));
  mit++;
 } // while
 
 // 문4) 정렬된 sortedMap으로 주어진 결과와 같은 화면이
 // 인쇄될 수 있도록 코드를 작성하십시오.
 
 map<string, int>::iterator mit2 = sortedMap.begin();
 
 while (mit2 != sortedMap.end()) {
  cout << mit2->first << "," << mit2->second << endl;
  mit2++;
 }// while
 
 system("PAUSE");
 return 0;
}


안녕하세요 엘체프 GG 임돠

DB대신 map에 데이터를 넣어 이용할 수 있는 login 문제입니다.

 

실행/출력 결과 예시)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <iostream>
#include <string>
#include <map>
 
using namespace std;
 
int main(void) {
 
 string id;
 string pw;
 
 // 문1) id/pw 입력 부분 완성
 // 시작
 
 
 
 // 끝
 
 // 문2) map 객체 변수를 생성하고, 주어진 데이터를
 // map 객체에 대입.
 // ID/PW는 각각 아래와 같이 2가지 세트를 대입합니다. 
 // ID : abcd, PW : 1234
 // ID : a1234, PW : 5678 
 // 대입한 map 객체의 데이터를 연속적으로 화면 인쇄 !
 
 // 시작
 
 
 
 // 끝
 
 
 // 입력한 id/pw를 map 객체의 id/pw와 비교하여
 // 메시징하는 부분 -> 이중 if !
 // id 존재여부 점검 -> pw 존재 여부 점검
 
 map<string, string>::iterator it
    = mapLogin.find(id);
 
 if (it == mapLogin.end()) {
 
        cout << "아이디가 존재하지 않습니다." << endl;
  } else {
 
   if (id == (*it).first) {
 
      if (pw == (*it).second) {
         cout << "패쓰워드가 일치합니다." << endl;
      } else {
         cout << "패쓰워드가 일치하지 않습니다." << endl;
      } // if
 
   } 
  
  }
 
 system("PAUSE");
 return 0;
}

 

-답안

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <iostream>
#include <string>
#include <map>
 
using namespace std;
 
int main(void) {
    string id;
    string pw;
 
    // 문1) id/pw 입력 부분 완성
    cout << "아이디를 입력하십시오 : ";
    cin >> id;
 
    // cout << endl;
    cout << "패쓰워드를 입력하십시오 : ";
    cin >> pw;
    cout << endl;
 
    cout << id << "," << pw << endl;
 
    // 문2) map 객체 변수를 생성하고, 주어진 데이터를
    // map 객체에 대입.
    // ID/PW는 각각 아래와 같이 2가지 세트를 대입합니다. 
    // ID : abcd, PW : 1234
    // ID : a1234, PW : 5678 
    // 대입한 map 객체의 데이터를 연속적으로 화면 인쇄 ! 
 
    map<string, string> mapLogin;
 
    mapLogin.insert(make_pair("abcd""1234"));
    mapLogin.insert(make_pair("a1234""5678"));
 
    /*
    map<string, string>::reverse_iterator it
    = mapLogin.rbegin();
    while (it !=mapLogin.rend()) {
    cout << it->first << "," << it->second << endl;
    it++;
    } // for
    */
 
    // 입력한 id/pw를 map 객체의 id/pw와 비교하여
    // 메시징하는 부분 -> 이중 if !
    // id 존재여부 점검 -> pw 존재 여부 점검 
 
    map<string, string>::iterator it
        = mapLogin.find(id);
 
    if (it == mapLogin.end()) {
 
        cout << "아이디가 존재하지 않습니다."
            << endl;
    }
    else {
 
        if (id == (*it).first) {
 
            if (pw == (*it).second) {
                cout << "패쓰워드가 일치합니다." << endl;
            }
            else {
                cout << "패쓰워드가 일치하지 않습니다."
                    << endl;
            } // if
 
        }
    }
 
    system("PAUSE");
    return 0;
}
cs

 

감사합니다.

'스터디 > C,C++' 카테고리의 다른 글

비속어 필터링(trash talk filtering) 문제  (6) 2018.03.05
map 정렬 문제  (6) 2018.03.05
C 문자열(string) 분리  (6) 2018.02.28
C 문자열(string) 바꾸기  (6) 2018.02.28
마지막 C 시험문제 공백 사각찍기  (7) 2018.02.28

안녕하세요 엘체프 GG 임돠

문자열분리 해보는 문제 입니다.

 

문) 아래와 같이 문자열이 주어졌을 때 출력 결과가 정렬되어 나올 수 있도록 프로그램을 작성하십시오.

(부분 완성 문제)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <iostream>
#include <string>
#include <sstream>
#include <list>
#include <vector>
 
// 문장을 입력받아서 단어로 분리. 단, 특수 문자는 제외시키도록 조치.
using namespace std;
 
string replaceSpecWord(string str);
list<string> splitSentence(string sent);
 
string replaceSpecWord(string str) {
 
   string word = " \t\n.,!?:;-";
   size_t found = str.find_first_of(word);
 
   while (found != string::npos)
   {
     str.replace(found, word.length(), "");
     found = str.find(word, found+1);
   }
 
   return str;
}
 
list<string> splitSentence(string sent) {
 
   list<string> strList;
   string temp;
   istringstream iss;
 
   iss.str(sent);
 
 
   while (iss >> temp) {
      temp= replaceSpecWord(temp);
      strList.push_back(temp);
   }
 
   return strList;
}
 
 
int main(void) {
 
   string sent = "내일은, 99주년. 3월1일\t 삼일절입니다!";
   list<string> wList = splitSentence(sent);
 
   // 나머지 부분을 완성하십시오.
   // 힌트) 문자열 변수에 반복자 패턴을 결합하여 인쇄한다.  
        
   
 
 
   system("PAUSE");
   return 0;
}

 

 

-답

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <string>
#include <sstream>
#include <list>
#include <vector> 
 
// 문장을 입력받아서 단어로 분리. 단, 특수 문자는 제외시키도록 조치.
using namespace std;
 
string replaceSpecWord(string str);
list<string> splitSentence(string sent);
 
string replaceSpecWord(string str) {
 
    string word = " \t\n.,!?:;-";
    size_t found = str.find_first_of(word);
    while (found != string::npos)
    {
        str.replace(found, word.length(), "");
        found = str.find(word, found + 1);
    }
    return str;
 
}
 
list<string> splitSentence(string sent) {
    list<string> strList;
    string temp;
    istringstream iss;
    iss.str(sent);
 
    while (iss >> temp) {
        temp = replaceSpecWord(temp);
        strList.push_back(temp);
    }
 
    return strList;
}
 
int main(void) {
    string sent = "내일은, 99주년. 3월1일\t 삼일절입니다!";
    list<string> wList = splitSentence(sent);
    // 나머지 부분을 완성하십시오.
    list<string>::iterator it = wList.begin();
 
    while (it != wList.end()) {
        cout << *it++ << endl;
    } // while 
 
    system("PAUSE");
 
    return 0;
 
}
cs

 

 

감사합니다.

 

 

 

 

 

 

 

'스터디 > C,C++' 카테고리의 다른 글

map 정렬 문제  (6) 2018.03.05
C++ map을 이용한 login 문제  (6) 2018.02.28
C 문자열(string) 바꾸기  (6) 2018.02.28
마지막 C 시험문제 공백 사각찍기  (7) 2018.02.28
C++ 문자열 경사면 인쇄하기  (9) 2018.02.19

안녕하세요 엘체프 GG 임돠

C 문자열을 바꾸는 소스 올립니다.

 

문) "C언어는 객체지향 언어이다." 라는 말을 지역변수로 입력받아서

"C언어는 구조적 언어이다."로 변경하는 프로그램을 작성하십시오.

 

-답

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
using namespace std;
 
void main() {
 
    // string str("C언어는 객체지향 언어이다.");
    string str = "C언어는 객체지향 언어이다.";
    string oriWord = "객체지향";
    string repWord = "구조적";
    size_t found = str.find(oriWord);
 
    while (found != string::npos) {
        str.replace(found, oriWord.length(), repWord);
        found = str.find(repWord, found + 1);
    }
    
    cout << str << endl;
    system("PAUSE");
}
cs

 

감사합니다.

'스터디 > C,C++' 카테고리의 다른 글

C++ map을 이용한 login 문제  (6) 2018.02.28
C 문자열(string) 분리  (6) 2018.02.28
마지막 C 시험문제 공백 사각찍기  (7) 2018.02.28
C++ 문자열 경사면 인쇄하기  (9) 2018.02.19
C++ 클래스 실습과제  (7) 2018.02.19

아래의 제시된 플로우차트를 참고하여 주어진 결과를 인쇄할 수 있도록 코드를 작성하여 제출하십시오.

1.출력결과

 

2.플로우차트

잘안보이네요......

바로 첨부파일

C언어과정수행평가서-(피평가자용)_남근곤.hwp

 -답

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
typedef unsigned int unit; /*int를 사용하기 위해*/
#include <stdio.h> /* printf사용시 */
#include <stdlib.h> /* systemf사용시 */
#define LINE_NUM /* 5를 사용하기 위해*/
 
int main()
{
    unit i, j;
    for (int i = 0; i < LINE_NUM; i++){// 5번 반복. 바깥쪽 루프는 세로 방향
        for (int j = 0; j < LINE_NUM -1- i; j++){ // 5번 반복. 안쪽 루프는 가로 방향
            printf("%c"' ');// 공백 출력
        }
        for (j = 0; j <LINE_NUM ; j++){
            printf("%c"'*');// 별표 출력
 
        }
        printf("\n");// 가로 방향으로 별을 다 그린 뒤 다음 줄로 넘어감
    }
    system("pause");
    return 0;
}
cs

 

C 공부 다시 해야겠다......

 

감사합니다.

 

'스터디 > C,C++' 카테고리의 다른 글

C 문자열(string) 분리  (6) 2018.02.28
C 문자열(string) 바꾸기  (6) 2018.02.28
C++ 문자열 경사면 인쇄하기  (9) 2018.02.19
C++ 클래스 실습과제  (7) 2018.02.19
C++ 클래스 응용 소스  (6) 2018.02.19

안녕하세요 엘체프 GG 입니다.

배열 관련된 문제입니다.


문) 아래와 같은 결과가 나올 수 있도록 반복문(for)을 이용하여 프로그램을 완성하십시오. 

        
문자 배열 :  char arr_c[8] = "abcdefg";


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <stdio.h>
#include <stdlib.h>
 
int main() {
 
 char arr_c[8] = "abcdefg";
 
 int i,j;
 
 for (i=0; i<4; i++) {
  
  for (j=0; j<5-i; j++) {
   printf("%c"' ');
  }
 
  // 시작 

  // 끝

  printf("\n");
 }
 system("PAUSE");
 return 0;
}



답:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <stdio.h>
#include <stdlib.h>
 
int main() {
 
    char arr_c[8] = "abcdefg";
 
    int i, j;
 
    for (i = 0; i<4; i++) {
 
        for (j = 0; j<5 - i; j++) {
            printf("%c", ' ');
        }
 
        // 시작
        for (j = i; j<2 * i + 1; j++) {
            printf("%c", arr_c[j]);
        }
        // 끝
        printf("\n");
    }
    system("PAUSE");
    return 0;
}

이상 감사합니다.

'스터디 > C,C++' 카테고리의 다른 글

C 문자열(string) 바꾸기  (6) 2018.02.28
마지막 C 시험문제 공백 사각찍기  (7) 2018.02.28
C++ 클래스 실습과제  (7) 2018.02.19
C++ 클래스 응용 소스  (6) 2018.02.19
C 문자열 거꾸로 출력하기  (8) 2018.02.12

안녕하세요 엘체프 입니다.

오늘 공부한 클래스 실습과제 임돠


Q.사각형 영역을 저장하고 처리하는 클래스 만드세요. 파워포인트나 포토샵 같은 프로그램에서 마우스를 드래그해서 사각형 영역을 선택하고, 선택된 영역을 다시 마우스로 드래그해서 이동하거나 크기를 조절하는 등의 조작을 해 보았을 겁니다. 이런 프로그램을 만들 때 활용할 수 있을 법한 클래스를 만들고자 하는 것입니다


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
#pragma once
class Region
{
public:
    Region(void);            // 생성자
    Region(int l, int t, int r, int b);    // 생성자
 
private:
    /////////////////////////////////////////////////////////////
    // 사각형 영역을 저장하기 위한 멤버변수들
    int left;                // 시작점의 x좌표
    int top;                // 시작점의 y좌표
    int right;                // 끝점의 x좌표
    int bottom;                // 끝점의 y좌표
 
    /////////////////////////////////////////////////////////////
    // 출력방식을 지정하기 위한 멤버변수
    static int notation;            // POINT_POINT 또는 POINT_SIZE
public:
    enum { POINT_POINT, POINT_SIZE };    // 시작점과 끝점, 시작점과 길이
 
public:
    /////////////////////////////////////////////////////////////
    // 사각형 영역에 대한 정보를 얻는 함수들
    int GetWidth() const;                    // 가로길이 얻기
    int GetHeight() const;                    // 세로길이 얻기
    void GetStartPoint(int &x, int &y) const;        // 시작점 얻기
    void GetEndPoint(int &x, int &y) const;        // 끝점 얻기
    void GetCenterPoint(int &x, int &y) const;        // 중심점 얻기
    bool IsPointInRegion(int x, int y) const;        // 점이 영역 안에 있는지
 
    /////////////////////////////////////////////////////////////
    // 사각형 영역을 설정하고 처리하는 함수들
    void SetRect(int l, int t, int r, int b);                // 영역 설정
    void Move(int x, int y);                        // 위치 이동
    void Resize(int width, int height);                    // 크기 변경
    void UnionRegion(const Region &r1, const Region &r2);        // 교집합
    void IntersectRegion(const Region &r1, const Region &r2);    // 합집합
 
    /////////////////////////////////////////////////////////////
    // 사각형 영역을 표시하기 위한 함수들
    void Show(void);                        // 영역 출력
    static void SetNotation(int notation);        // 출력 방식 지정
};
-----------------------------------------------------------------------------------
 
#include <stdio.h>
#include <iostream>
//c언어의 stude.h와 같은 역활의 header
#include "Region.h"
 
int Region::notation = Region::POINT_POINT;
 
Region::Region(void)
{
    SetRect(0000);    // 영역을 0으로 초기화
}
Region::Region(int l, int t, int r, int b)
{
    SetRect(l, t, r, b);    // 영역을 주어진 값으로 초기화
}
 
void Region::SetRect(int l, int t, int r, int b)
{
    left = l;            // 시작점의 x좌표 설정
    top = t;            // 시작점의 y좌표 설정
    right = r;            // 끝점의 x좌표 설정
    bottom = b;            // 끝점의 y좌표 설정
}
int Region::GetWidth() const
{
    return right - left;
}
int Region::GetHeight() const
{
    return bottom - top;
}
void Region::GetStartPoint(int &x, int &y) const
{
    x = left;        // 시작점의 x 좌표 얻기
    y = top;        // 시작점의 y좌표 얻기
}
void Region::GetEndPoint(int &x, int &y) const
{
    x = right;        // 끝점의 x 좌표 얻기
    y = bottom;        // 끝점의 y좌표 얻기
}
void Region::GetCenterPoint(int &x, int &y) const
{
    x = (left + right) / 2;    // 중심점의 x 좌표 얻기
    y = (top + bottom) / 2;    // 중심점의 y좌표 얻기
}
 
bool Region::IsPointInRegion(int x, int y) const
{
    return (x >= left && x <= right && y >= top && y <= bottom);
}
void Region::Move(int x, int y)
{
    left += x;            // 시작점의 x좌표 이동
    right += x;            // 끝점의 x좌표 이동
    top += y;            // 시작점의 y좌표 이동
    bottom += y;        // 끝점의 y좌표 이동
}
 
void Region::Resize(int width, int height)
{
    int x, y;
    GetCenterPoint(x, y);    // 중심점 좌표 얻기
    left = x - width / 2;    // 중심으로부터 가로길이의 절반만큼 이동
    top = y - height / 2;    // 중심으로부터 세로길이의 절반만큼 이동
    right = left + width;    // 가로길이가 width가 되도록 조절
    bottom = top + height;    // 세로길이가 height가 되도록 조절
}
void Region::UnionRegion(const Region &r1, const Region &r2)
{
    left = r1.left > r2.left ? r1.left : r2.left;
    right = r1.right < r2.right ? r1.right : r2.right;
    top = r1.top > r2.top ? r1.top : r2.top;
    bottom = r1.bottom < r2.bottom ? r1.bottom : r2.bottom;
    if (left >= right || top >= bottom)      // 교집합이 존재하지 않는 경우
    {
        left = top = right = bottom = 0;
    }
}
 
void Region::IntersectRegion(const Region &r1, const Region &r2)
{
    left = r1.left < r2.left ? r1.left : r2.left;
    right = r1.right > r2.right ? r1.right : r2.right;
    top = r1.top < r2.top ? r1.top : r2.top;
    bottom = r1.bottom > r2.bottom ? r1.bottom : r2.bottom;
}
void Region::SetNotation(int n)
{
    notation = n;
}
 
void Region::Show(void)
{
    if (notation == POINT_POINT)    // 시작점/끝점 형식
    {
        printf("(%d, %d), (%d, %d)\n", left, top, right, bottom);
    }
    else                    // 시작점/가로, 세로/길이 형식
    {
        printf("(%d, %d), [%d x %d]\n", left, top, GetWidth(), GetHeight());
    }
}
 
------------------------------------------------------------------------------------------
 
#include <iostream>
#include "Region.h"
 
using namespace std;
 
int main(void)
{
    Region::SetNotation(Region::POINT_POINT);    // 출력 형식 지정
    Region r1(1010100100);        // 영역 r1 선언
    Region r2(5050120120);        // 영역 r2 선언
    Region r3;
 
    r3.IntersectRegion(r1, r2);        // r1과 r2의 교집합을 r3에 저장
    r3.Show();
    r3.UnionRegion(r1, r2);            // r1과 r2의 합집합을 r3에 저장
    r3.Show();
    r3.Move(100100);            // r3의 위치 이동
    r3.Show();
    r3.Resize(200200);            // r3의 크기 변경
    r3.Show();
 
    Region::SetNotation(Region::POINT_SIZE);    // 출력 형식 변경
    r1.Show();
    r2.Show();
    r3.Show();
 
    system("PAUSE");
    return 0;
}
cs



이상 감사합니다.


'스터디 > C,C++' 카테고리의 다른 글

마지막 C 시험문제 공백 사각찍기  (7) 2018.02.28
C++ 문자열 경사면 인쇄하기  (9) 2018.02.19
C++ 클래스 응용 소스  (6) 2018.02.19
C 문자열 거꾸로 출력하기  (8) 2018.02.12
C 문자열 자르기 문제  (7) 2018.02.12

안녕하세요 엘체프 GG 입니다.

머리에는 안들어오지만 벌써 C++ 들어 왔네요.

객체지향이 시작되는데... 소스만 끄적여 볼꼐요.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#pragma once
class Point
{
     
private : 
    int x, y;// 캡슐화(
public:
    int x, y;//x,y좌표 맴버(필드)변수선언
    //생성자,소멸자: 맴버 메서드(함수)
    //reture 자료형을 표시(x)
    //반드시 클래스와 동명!!
    //자바에서는 소멸자(X)
    //생성자(constructor)
    //소멸자(destructor)
    //기본 생성자,소멸자 묵시적 (implicit) 선언 가능.
 
    Point();//기본 생성자(구축자)
    ~Point(); //기본 소멸자
    //기본 생성자,소멸자 안 써도 된다. 
 
    //생성자 오버로딩(overloding)
    Point(int x, int y);
    
    //일반 맴버 메서드 : 추상 메서드(함수의 선언부) :
    //함수의 몸통이 없고 선언부만 있는 함수
    //메뉴, 설계도의 역활
    void setPosition(int _x, int _y);
    void Move(int _x, int _y);
    void Show(void);
};
 
----------------------------------------------------------------------------------------------------
 
#include <iostream>
//c언어의 stude.h와 같은 역활의 header
#include "Point.h"
 
using namespace std//
 
//header 파일(추상부) --> 몸통(body) : 구현부, 구체부, 실체화, 구상
//implementaion, realization, concrete
//기본 생성자
Point::Point(void)
{
    cout << "기본생성자 입니다." << endl;
}
 
 
Point::~Point(void)
{
    cout << "기본 소멸자 입니다." << endl;
}
//set-method = setter : 설정(대입)하는 함수
void Point::setPosition(int _x, int _y){
 
    cout << "SetPosition 임돠" << endl;//log기록
    x = _x;//맴버 필드 <--인자(대입)
    y = _y;
 
}
 
void Point::Move(int x, int y){
 
    cout << "Move 함수임돠" << endl;
    this->+= x; //증가 이동 한다.
    this->+= y;
}
 
void Point::Show(void){
    cout << "Show 출력하는놈이다" << endl;
    cout << "(" << x <<"," <<y<<")" << endl;
}
 
Point::Point(int x, int y){
    cout << "오버로딩된 생성자" << endl;
    this->= x;
    this->= y;
}
 
------------------------------------------------------------------------------------------------------------
 
 
#include <iostream>
#include "Point.h"
 
using namespace std;
 
int main(void){
    Point p1, p2(10,10);
    // 객체 변수(인스턴스) 선언,생성
    //p1 : 기본 생성자 묵시적 사용
    //p2(10,10) : 오버로딩된 생성자
    //메서드명 묵시적 사용, 인자는 명시적 사용
    //Java : Point p1 = new Point();, new,생성자가 명시적으로 사용되어야함!
    //C++ 생성자가 미사용(X), 객저 생성시 묵시적 언급!
 
    p1.setPosition(2030);
    //p1.x = 20;//초기화에 20을 대입
    //p1.y = 30;
 
    p1.Move(100100);
    p2.Move(200200);
 
    p1.Show();
    p2.Show();
 
    system("PAUSE");
    return 0;
}
 
 
cs



이상 감사합니다.

'스터디 > C,C++' 카테고리의 다른 글

C++ 문자열 경사면 인쇄하기  (9) 2018.02.19
C++ 클래스 실습과제  (7) 2018.02.19
C 문자열 거꾸로 출력하기  (8) 2018.02.12
C 문자열 자르기 문제  (7) 2018.02.12
구조체  (6) 2018.02.05

다운로드 

문) 아래와 같이 제시된 문자열을 역순으로 화면에 인쇄할 수 있도록 프로그램하십시오.

단, 문자열의 길이를 측정할 경우 string.h 소속의 strlen 함수를 사용하고 문자열의 인쇄는 반복문을 활용합니다.
아래 해당되는 코드의 일부분을 완성하십시오.

strPtr = "green academy c nightline";




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main() {
 
 char *strPtr = NULL;
 strPtr = "green academy c nightline";
 int i;
 int sizeStr = strlen(strPtr);
 
 // 이 부분의 코드를 완성하십시오. 


 
 printf("\n");
 system("PAUSE");
}



-----------------------------------------------------------




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
int main() {
 
    char *strPtr = NULL;
    strPtr = "green academy c nightline";
    int i;
    int sizeStr = strlen(strPtr);//strlen 함수로 sizeStr 라는변수에 문자열의 길이를 저장 
 
    ///////////////////////////////////////////
    char strPtr2[] = "green academy c nightline";
 
    int sizeStr2 = sizeof(strPtr2) / sizeof(char);
 
    // 주의사항) strlen과 위의 경우 길이 편차로 인해
    // 반복문으로 인쇄할 경우 주의가 필요하다.
 
    printf("strlen 사용 길이 : %d\n", sizeStr); // 25
    printf("sizeof 사용 길이 : %d\n", sizeStr2); // 25+1 = 26
    ////////////////////////////////////
 
    for (i = sizeStr - 1; i >= 0; i--//sizeStr-1(index가0부터니) 부터 0까지 내림차순으로 strPtr 문자열을 출력    
    {
        printf("%c", strPtr[i]);
    }    
    printf("\n");
    system("PAUSE");
}
cs


'스터디 > C,C++' 카테고리의 다른 글

C++ 클래스 실습과제  (7) 2018.02.19
C++ 클래스 응용 소스  (6) 2018.02.19
C 문자열 자르기 문제  (7) 2018.02.12
구조체  (6) 2018.02.05
배열포인터활용 성적구하기  (7) 2018.01.31

+ Recent posts